Node.js NPM
NPM is Node's package manager — learn how to initialize a project, install dependencies, and run scripts with package.json.
What Is npm?
npm (Node Package Manager) installs alongside Node.js and gives you access to the npm registry, the largest collection of open-source JavaScript packages. It also manages your project's dependencies and defines custom scripts through a single file: package.json. Run npm init to generate one interactively, or npm init -y to accept all the defaults instantly.
package.json
{
"name": "my-node-app",
"version": "1.0.0",
"description": "A sample Node.js project",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"no tests yet\" && exit 0"
},
"dependencies": {},
"devDependencies": {}
}npm Scripts
index.js
// index.js — the script executed by "npm start"
console.log("Server starting...");
console.log("NODE_ENV:", process.env.NODE_ENV || "development");
// package.json: "scripts": { "start": "node index.js" }
// Run with: npm startInstalling Dependencies
Use npm install <package> to add a dependency. npm downloads the package into a node_modules folder, records it in package.json, and locks exact versions in package-lock.json so every machine installs the identical dependency tree.
- npm install express — adds a runtime dependency your app needs to function.
- npm install --save-dev nodemon — adds a devDependency, needed only during development.
- npm install — with no package name, installs everything already listed in package.json.
- npm uninstall <package> — removes a dependency and updates package.json.
Dependencies vs. devDependencies
version-check.js
// version-check.js
const pkg = require("./package.json");
console.log(`${pkg.name} v${pkg.version}`);
console.log("Start script:", pkg.scripts.start);
// Run with: node version-check.js
// Output:
// my-node-app v1.0.0
// Start script: node index.jsExercise: Node.js NPM
What is npm primarily used for?