Node.js ยท Chapter 6 of 43

npm & package.json

npm (Node Package Manager) is the tool used to install, manage and share JavaScript packages. Every Node.js project usually has a `package.json` file describing it.

package.json lists your project's dependencies, scripts, version, and metadata, making projects reproducible on any machine.

Creating package.json

Run `npm init -y` to quickly generate a default package.json file for your project.

Installing packages

Use `npm install <package>` to add a dependency; it gets recorded in package.json and installed into node_modules.

Example 1 (javascript)
npm init -y
npm install express
Output
{
  "name": "my-app",
  "dependencies": { "express": "^4.18.2" }
}

npm init creates the file; installing express adds it as a dependency.

Example 2 (javascript)
// package.json scripts
"scripts": {
  "start": "node app.js"
}
// then run:
// npm start

The scripts section lets you define shortcuts like `npm start` or `npm test`.

Key points

  • package.json describes a Node.js project.
  • npm install adds dependencies and updates package.json.
  • node_modules stores installed packages.
  • The scripts field defines custom CLI commands.
๐Ÿ’ก Note: Never edit node_modules by hand โ€” it's regenerated from package.json and package-lock.json.

๐Ÿ“ Quick Quiz

1. What command creates a default package.json?

2. Where are installed packages stored?

3. What runs the 'start' script defined in package.json?