npm (Node Package Manager) is a package manager for Node.js, enabling developers to easily install, update, uninstall, and share JavaScript libraries or modules. It is the default package manager for Node.js and hosts one of the world’s largest software registries, with hundreds of thousands of reusable code modules.
npm Basics
Introduction to npm
- npm is installed alongside Node.js, so once Node.js is installed, npm commands are available in the terminal.
- The npm registry is an online database storing all available packages, from which you can download and install packages.
- The
package.jsonfile is central to an npm package, containing metadata such as name, version, description, author, and dependencies.
npm init
The npm init command creates a new package.json file. When run in a new project, npm prompts for details about the project, including:
- name: The project’s name.
- version: The project’s version, typically defaulting to “1.0.0”.
- description: A brief project description.
- main: The main entry file for the project.
- license: The type of license used.
- author: Information about the project author.
- contributors: Information about project contributors.
- dependencies: Modules required for runtime.
- devDependencies: Modules needed only during development.
You can press Enter to accept defaults or provide custom values. After completion, the package.json file is generated in the project’s root directory.
Installing Packages
- Use
npm install <package-name>to install a package. This adds it to thenode_modulesdirectory and records it inpackage.jsonunderdependencies. - For development dependencies, use
npm install --save-dev <package-name>ornpm i -D <package-name>, adding the package todevDependencies. - Install a specific version with
npm install <package-name>@<version>.
Uninstalling Packages
- Use
npm uninstall <package-name>to remove an installed package. If listed independenciesordevDependencies, include--saveor--save-devto updatepackage.json.
Updating Packages
- Use
npm update <package-name>to update an installed package to its latest version.
Other Common Commands
npm list: Lists all dependencies in the current project.npm outdated: Shows dependencies that can be updated.npm run <script>: Executes scripts defined inpackage.json.
npm Configuration and Commands
package.json
The package.json file is the core of every npm project, defining basic project information and dependencies. When initializing a project with npm init, this file is created. Common fields include:
name: Project name.version: Current version.description: Project description.main: Main entry file.scripts: Custom script commands.dependencies: Modules required to run the project.devDependencies: Modules needed during development.
npm Configuration
Configuration Files
npm configuration is managed through .npmrc files, located in the user’s home directory (global), project root (project-specific), or other directories (local). Configuration options include:
prefix: Specifies the installation path for global modules.cache: Specifies the cache directory.registry: Specifies the source of npm packages, which can be a private registry or mirror.
Viewing Configuration
Use npm config get <option> to view a specific configuration item or npm config list to see all configurations.
Modifying Configuration
Use npm config set <option> <value> to modify configuration items.
npm Commands
Installation
npm install <package>: Installs a specified package.npm install <package>@<version>: Installs a specific version of a package.npm install --save <package>: Installs and saves todependencies.npm install --save-dev <package>: Installs and saves todevDependencies.
Uninstallation
npm uninstall <package>: Uninstalls a package.npm uninstall --save <package>: Uninstalls and removes fromdependencies.npm uninstall --save-dev <package>: Uninstalls and removes fromdevDependencies.
Update
npm update <package>: Updates a specified package to the latest version.npm update: Updates all packages to the latest versions.
Listing
npm list: Lists all installed packages.npm list <package>: Lists the version and dependencies of a specific package.
Search
npm search <keyword>: Searches the npm registry for a keyword.
Publish
npm publish: Publishes the current project to the npm registry.
Scripts
npm run <script>: Executes a script defined inpackage.json.
Other
npm init: Initializes a project and createspackage.json.npm outdated: Displays packages that can be updated.
Example Code Analysis
Suppose we have a simple project and want to use the Express framework. Here’s how to initialize and install Express using npm:
Create and enter the project directory:
mkdir my-project
cd my-projectInitialize the project:
npm init -yThis generates a default package.json file.
Install Express and add it as a dependency:
npm install express --saveCheck package.json to see express added under dependencies.
Create a simple Express server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});Add a start script to run the server:
"scripts": {
"start": "node index.js"
}Start the server:
npm startThese steps demonstrate using npm to create a basic Express application, configuring dependencies and scripts to run the server.
npm Package Management
npm Installation and Environment Setup
Installing Node.js
npm is bundled with Node.js. Ensure compatibility by checking versions with node -v and npm -v.
Configuring npm
- Global Configuration: Edit
~/.npmrc. - Project Configuration: Create
.npmrcin the project root.
npm Basic Commands
Initialize a Project
npm initAnswer prompts to generate package.json.
Install a Package
npm install <package-name>Installs the latest version, saving to dependencies.
Install a Specific Version
npm install <package-name>@<version>Install Development Dependencies
npm install <package-name> --save-devUninstall a Package
npm uninstall <package-name>Update a Package
npm update <package-name>List Packages
npm listSearch Packages
npm search <keyword>npm Scripts
Define scripts in package.json, e.g.:
"scripts": {
"start": "node server.js",
"test": "mocha test/*.js"
}Run Scripts:
npm run startnpm Configuration
Set the npm registry source:
npm config set registry <url>View Configuration:
npm config get <option>npm Publishing
- Create an npm Account Register at https://www.npmjs.com/.
Login
npm loginPublish a Package
npm publishAdvanced npm Usage
Link Local Packages
npm linkand
npm link <package-name>Use Private Registries
For example, Verdaccio or Nexus.
Scoped Namespaces
Use packages in the form @scope/package.
Example Code Analysis
Suppose we want to create a simple npm package containing a function library.
Create a Project
mkdir my-package
cd my-package
npm init -yWrite Code
Create src/index.js:
module.exports = {
add: function(a, b) {
return a + b;
}
};Write Tests
Create test/index.test.js:
const assert = require('assert');
const lib = require('../src/index');
describe('Add Function', function() {
it('should return the sum of two numbers', function() {
assert.strictEqual(lib.add(1, 2), 3);
});
});Install Testing Framework
npm install mocha chai --save-devAdd Scripts
Edit package.json:
"scripts": {
"test": "mocha"
}Run Tests
npm testPublish the Package
Log in to npm, then:
npm publishUsing npm Scripts
npm Scripts Basics
Creating package.json
Initialize a project with npm init to generate package.json.
Adding Scripts
Define script commands in the scripts field of package.json. For example:
{
"name": "my-project",
...
"scripts": {
"start": "node server.js",
"test": "jest",
"lint": "eslint .",
"build": "webpack --mode production",
"deploy": "npm run build && gh-pages -d dist"
},
...
}Running npm Scripts
Run scripts with npm run <script-name>. For example, to run tests:
npm run testAdvanced npm Scripts
Environment Variables
Use environment variables in scripts:
"scripts": {
"start": "NODE_ENV=production node server.js"
}Chaining Scripts
Use && and || to chain commands:
"scripts": {
"prepublish": "npm run lint && npm run test",
"postinstall": "node postInstall.js"
}Conditional Execution
Use shell syntax for conditional execution:
"scripts": {
"deploy": "[[ ! -z $GITHUB_TOKEN ]] && npm run build && gh-pages -d dist"
}npm Lifecycle Scripts
preinstall and postinstall
Execute scripts before and after dependency installation.
prepublish and postpublish
Run scripts before and after publishing a package.
pretest and posttest
Execute scripts before and after running tests.
npm Scripts and Environments
Development Environment
Define scripts for development, like hot-reload servers.
Production Environment
Define scripts for building and deploying.
Integrating npm Scripts with Tools
Babel
Compile ES6+ code:
"scripts": {
"build": "babel src --out-dir dist"
}Webpack
Bundle modules:
"scripts": {
"build": "webpack --mode production"
}Jest
Run unit tests:
"scripts": {
"test": "jest"
}ESLint
Check code quality:
"scripts": {
"lint": "eslint ."
}Best Practices for npm Scripts
Keep Scripts Simple
Avoid complex logic in package.json.
Use Environment Variables
Ensure script flexibility and security.
Document Scripts
Explain script purposes and usage in the README.
Test Scripts
Verify scripts work across different environments.
Example Code Analysis
Create a Project
mkdir my-project
cd my-project
npm init -yAdd Scripts
Edit package.json:
{
"name": "my-project",
...
"scripts": {
"start": "node server.js",
"test": "jest",
"lint": "eslint .",
"build": "webpack --mode production",
"deploy": "npm run build && gh-pages -d dist"
},
...
}Run Scripts
npm run start



