npm install
- Node.js course
- Intermediate
- Lesson 70/116
- 4 min
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.
Practice 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.
Starter code
// Define the package.json content as a string
// Parse it into an object with JSON.parse
// Print the dependencies count
// write hereSample solution
const content = '{"name":"my-app","dependencies":{"express":"^4.18.0"}}';
const pkg = JSON.parse(content);
console.log(Object.keys(pkg.dependencies).length);Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does npm install express download the package to?
npm install express- Into package.json
- Into the node_modules folder Correct answer
- Into the global space
- Into the dist folder
Explanation: Package files are downloaded into the node_modules folder.
2 Complete the install command
npm ____ express
npm install express
Explanation: npm install express downloads the package.
3 Match each piece to its role
| Term | Meaning |
|---|---|
npm install |
Installs a package |
node_modules |
Path of packages |
package.json |
Dependency list |
registry |
Package repository |