Node.js NPM

NPM is Node's package manager — learn how to initialize a project, install dependencies, and run scripts with package.json.

#Jobseeker

Find matching jobs & Auto apply with AI

Hyring
Jobseeker using Hyring to search, apply, and prepare with AI

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": {}
}
Note: Key fields: name and version identify the package, main points to the entry file, scripts defines named commands you run with npm run <name>, and dependencies/devDependencies list installed packages with their version ranges.

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 start

Installing 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

TypePurposeExample PackagesInstall Command
dependenciesRequired at runtime, in productionexpress, axiosnpm install <pkg>
devDependenciesOnly needed while developing or testingnodemon, jestnpm install -D <pkg>

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.js

Exercise: Node.js NPM

What is npm primarily used for?