Node.js
npm install
Learn to install packages with npm install.
npm install
npm install (short form npm i) downloads packages from the npm registry and saves them in the node_modules folder. It is the first step to use a package in a project.
For example, when you run npm install express, Express is downloaded, placed under node_modules/express/ and added to the dependencies section of package.json. You can install several packages at once: npm install express body-parser. After the install finishes you can use the package in code with require("express"). Packages are installed locally, so they only apply to that project.
Install flags
You can change the behavior of npm install with flags. --save-dev (short form -D) adds the package to devDependencies, for packages needed only during development.
--global (short form -g) installs the package system-wide, so it is available in every project. But global install is usually for CLI tools; it is not recommended for libraries. Without a flag, npm install express adds the package to dependencies. This separates packages by purpose: dependencies for production, devDependencies for development only.
Exercise Print the dependency count
Define a string named content with the value {"name":"my-app","dependencies":{"express":"^4.18.0"}}. Parse it into an object with JSON.parse. Print Object.keys(pkg.dependencies).length with console.log.
Show example solution
const content = '{"name":"my-app","dependencies":{"express":"^4.18.0"}}';
const pkg = JSON.parse(content);
console.log(Object.keys(pkg.dependencies).length);
Test yourself
-
Where does npm install express download the package to?
npm install express
- Into package.json
- Into the node_modules folder
- Into the global space
- Into the dist folder
Show answer
Into the node_modules folder — Package files are downloaded into the node_modules folder.
-
Complete the install command
npm ____ express
Show answer
npm install express
-
Match each piece to its role
- npm install
- Installs a package
- node_modules
- Path of packages
- package.json
- Dependency list
- registry
- Package repository
Next lesson: package.json scripts