NPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use.
- It is primarily used to manage packages or modules—these are pre-built pieces of code that extend the functionality of your NodeJS application.
- The NPM registry hosts millions of free packages that you can download and use in your project.
- NPM is installed automatically when you install NodeJS, so you don’t need to set it up manually.
Package in NodeJs
A package in NodeJS is a reusable module of code that adds functionality to your application. It can be anything from a small utility function to a full-featured library.
- Packages can be installed from the NPM registry.
- They are stored in the node_modules folder in your project.
- You can easily install, update, or remove packages with NPM commands.
How to Use NPM with NodeJS?
To start using NPM in your project, follow these simple steps
Step 1: Install NodeJS and NPM
First, you need to install NodeJS. NPM is bundled with the NodeJS installation. You can follow our article to Install the Node and NPM- How to install Node on your system
Step 2: Verify the Installation
After installation, verify NodeJS and NPM are installed by running the following commands in your terminal:
node -v
npm -v
These commands will show the installed versions of NodeJS and NPM.
NodeJS NPM VersionStep 3: Initialize a New NodeJS Project
In the terminal, navigate to your project directory and run:
npm init -y
This will create a package.json file, which stores metadata about your project, including dependencies and scripts.
Step 4: Install Packages with NPM
To install a package, use the following command
npm install <package-name>
For example, to install the Express.js framework
npm install express
This will add express to the node_modules folder and automatically update the package.json file with the installed package information.
Step 5: Install Packages Globally
To install packages that you want to use across multiple projects, use the -g flag:
npm install -g <package-name>
Step 6: Run Scripts
You can also define custom scripts in the package.json file under the "scripts" section. For example:
{
"scripts": {
"start": "node app.js"
}
}
Then, run the script with
npm start
Using NPM Package in the project
Create a file named app.js in the project directory to use the package
JavaScript
//app.js
const express = require('express');//import the required package
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
- express() creates an instance of the Express app.
- app.get() defines a route handler for HTTP GET requests to the root (/) URL.
- res.send() sends the response “Hello, World!” to the client.
- app.listen(3000) starts the server on port 3000, and console.log() outputs the server URL.
Now run the application with
node app.js
Visit http://localhost:3000 in your browser, and you should see the message: Hello, World!
Managing Project Dependencies
1. Installing All Dependencies
In a NodeJS project, dependencies are stored in a package.json file. To install all dependencies listed in the file, run:
npm install
This will download all required packages and place them in the node_modules folder.
2. Installing a Specific Package
To install a specific package, use:
npm install <package-name>
You can also install a package as a development dependency using:
npm install <package-name> --save-dev
Development dependencies are packages needed only during development, such as testing libraries.
To install a package and simultaneously save it in package.json file (in case using NodeJS), add --save flag. The --save flag is default in npm install command so it is equal to npm install package_name command.
Example:
npm install express --save
Usage of Flags:
- --save: flag one can control where the packages are to be installed.
- --save-prod : Using this packages will appear in Dependencies which is also by default.
- --save-dev : Using this packages will get appear in devDependencies and will only be used in the development mode.
Note: If there is a package.json file with all the packages mentioned as dependencies already, just type npm install in terminal
3. Updating Packages
You can easily update packages in your project using the following command
npm update
This will update all packages to their latest compatible versions based on the version constraints in the package.json file.
To update a specific package, run
npm update <package-name>
4. Uninstalling Packages
To uninstall packages using npm, follow the below syntax:
npm uninstall <package-name>
For uninstall Global Packages
npm uninstall package_name -g
Popular NPM Packages for NodeJS
NPM has a massive library of packages. Here are a few popular packages that can enhance your NodeJS applications
Packages | Description |
---|
Express | A fast, minimal web framework for building APIs and web applications. |
Mongoose | A MongoDB object modeling tool for NodeJS. |
Lodash | A utility library delivering consistency, customization, and performance. |
Axios | A promise-based HTTP client for making HTTP requests. |
React | A popular front-end library used to build user interfaces. |
Dotenv | Loads environment variables from a .env file into process.env. |
Nodemon | Automatically restarts the server during development when file changes are detected. |
Jest | A JavaScript testing framework designed to ensure correctness of any NodeJS code. |
Socket.io | Enables real-time, bidirectional communication between web clients and servers. |
Versioning in NPM
NPM allows you to manage package versions. This is important when you want to ensure that a specific version of a library is used across all environments.
Install a Specific Version
To install a specific version of a package, use:
npm install <package-name>@<version>
For example:
npm install [email protected]
This will install version 4.17.1 of Express, regardless of the latest version.
Using Semantic Versioning to manage packages

- To install a package of a specific version, mention the full and exact version in the package.json file.
- To install the latest version of the package, mention "*" in front of the dependency or "latest". This will find the latest stable version of the module and install it.
- To install any version (stable one) above a given version, mention it like in the example below: "express":"^4.1.1". in package.json file. The caret symbol (^) is used to tell the npm to find a version greater than 4.1.1 and install it.
Alternative to NPM: Yarn and pnpm
While NPM is the default package manager for NodeJS, there are alternatives like Yarn and pnpm. These tools aim to provide faster package installations and additional features but work in similar ways to NPM.
Best Practices for Using NPM in NodeJS Projects
- Use Semantic Versioning: Specify exact versions of dependencies in your package.json to ensure consistent environments across different setups.
- Regularly Audit Dependencies: Run npm audit to identify and fix known vulnerabilities in your project's dependencies.
- Avoid Publishing Secrets: Ensure that sensitive information like API keys or passwords are not included in your packages or version control.
Conclusion
NPM (Node Package Manager) is an essential tool for managing NodeJS packages and dependencies, making development more efficient and scalable. It allows developers to install, update, and manage libraries easily, supporting both local and global installations. With features like version control, dependency management, and automation scripts, NPM enhances the development workflow.
Similar Reads
Node.js Tutorial Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was earlier mainly used for frontend d
4 min read
Node.js Basic
NodeJS IntroductionNodeJS is a runtime environment for executing JavaScript outside the browser, built on the V8 JavaScript engine. It enables server-side development, supports asynchronous, event-driven programming, and efficiently handles scalable network applications. NodeJS is single-threaded, utilizing an event l
5 min read
How to Install Node.js on LinuxInstalling Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions.PrerequisitesA Linux System: such a
6 min read
How to Install Node.js on WindowsInstalling Node.js on Windows is a straightforward process, but it's essential to follow the right steps to ensure smooth setup and proper functioning of Node Package Manager (NPM), which is crucial for managing dependencies and packages. This guide will walk you through the official site, NVM, Wind
6 min read
NodeJS BasicsNodeJS is a powerful and efficient open-source runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, which helps in the creation of scalable and high-performance web applications. In this article, we will discuss the NodeJs Basics and
7 min read
Node First ApplicationNodeJS is widely used for building scalable and high-performance applications, particularly for server-side development. It is commonly employed for web servers, APIs, real-time applications, and microservices.Perfect for handling concurrent requests due to its non-blocking I/O model.Used in buildin
4 min read
NodeJS REPL (READ, EVAL, PRINT, LOOP)NodeJS REPL (Read-Eval-Print Loop) is an interactive shell that allows you to execute JavaScript code line-by-line and see immediate results. This tool is extremely useful for quick testing, debugging, and learning, providing a sandbox where you can experiment with JavaScript code in a NodeJS enviro
5 min read
NodeJS NPMNPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use.It is primarily used to manage packages or modulesâthese are
6 min read
NodeJS Global ObjectsIn NodeJS global objects are the objects that are accessible in the application from anywhere without explicitly using the import or require. In browser-based JavaScript, the window object is the global scope, meaning it holds all global variables and functions. In NodeJS, instead of the window obje
6 min read
NodeJS ModulesIn NodeJS, modules play an important role in organizing, structuring, and reusing code efficiently. A module is a self-contained block of code that can be exported and imported into different parts of an application. This modular approach helps developers manage large projects, making them more scal
6 min read
Node.js Local ModuleA local module in Node.js refers to a custom module created in an application. Unlike the built in or third-party modules, local modules are specific to the project and are used to organize and reuse your code across different parts of your application.Local Module in Node.jsLocal modules in Node.js
2 min read
Node.js Assert Module
Node.js Buffer Module
Node.js BuffersNode.js Buffers are used to handle binary data directly in memory. They provide a way to work with raw binary data streams efficiently, crucial for I/O operations, such as reading from files or receiving data over a network.Buffers in Node.jsBuffers are instances of the Buffer class in Node.js. Buff
4 min read
Node.js Buffer.copy() MethodBuffer is a temporary memory storage that stores the data when it is being moved from one place to another. It is like an array of integers. The Buffer.copy() method simply copies all the values from the input buffer to another buffer. Syntax:buffer.copy( target, targetStart, sourceStart, sourceEnd
2 min read
Node.js Buffer.includes() MethodBuffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like an array of integers. The Buffer.includes() method checks whether the provided value is present or included in the buffer or not. Syntax:buffer.includes( value, byteOffset, encodin
2 min read
Node.js Buffer.compare() MethodBuffer is a temporary memory storage that stores the data when it is being moved from one place to another. It is like an array of integers. Buffer.compare() method compares the two given buffers. Syntax: buffer1.compare( targetBuffer, targetStart, targetEnd, sourceStart, sourceEnd ) Parameters: Th
3 min read
Node.js Buffer.alloc() MethodThe Buffer.alloc() method is used to create a new buffer object of the specified size. This method is slower than Buffer.allocUnsafe() method but it assures that the newly created Buffer instances will never contain old information or data that is potentially sensitive. Syntax Buffer.alloc(size, fil
2 min read
Node.js Buffer.equals() MethodThe Buffer.equals() method is used to compare two buffer objects and returns True of both buffer objects are the same otherwise returns False. Syntax: buffer.equals( buf ) Parameters: This method accepts single parameter otherBuffer which holds the another buffer to compare with buffer object. Retur
1 min read
Node.js Buffer.subarray() MethodThe buffer.subarray() method is an inbuilt application programming interface of the buffer module which is used to crop a part of array i.e. create sub-array from an array.Syntax:Â Â Buffer.subarray( starting_index, ending_index ) Parameters: This method has two parameters as mentioned above and desc
3 min read
Node.js Buffer.readIntBE() MethodThe Buffer.readIntBE() method is used to read the number of bytes for a buffer at a given offset and interprets the result as a two's complement signed value. Syntax: buffer.readIntBE( offset, byteLen ) Parameters: This method accepts two parameters as mentioned above and described below: offset: It
2 min read
Node.js Buffer.write() MethodThe Buffer.write() method writes the specified string into a buffer, at the specified position. If buffer did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written. Syntax: buffer.write( string, offset, lengt
2 min read
Node.js Buffer Complete ReferenceBuffers are instances of the Buffer class in Node.js. Buffers are designed to handle binary raw data. Buffers allocate raw memory outside the V8 heap. Buffer class is a global class so it can be used without importing the Buffer module in an application. Example: JavaScript <script> // Node.js
8 min read
Node.js Console Module
Node.js ConsoleThe console module is essential for debugging and logging in Node.js applications. It enables developers to print messages to the terminal, making it easier to monitor application behavior, track issues, and display runtime information.Console in Node.js The console module in Node.js is a built-in u
4 min read
Node.js console.assert() MethodThe console.assert() method is an inbuilt application programming interface of the console module which is used to assert value passed to it as a parameter, i.e. it checks whether the value is true or not, and prints an error message, if provided and failed to assert the value. Syntax: console.asse
2 min read
Node.js console.clear() MethodThe console.clear() method is used to clear the stdout, when stdout is a TTY (Teletype) i.e. terminal it will attempt to clear the TTY. When stdout is not a TTY, this method does nothing. The console.clear() will work differently across different operating systems and terminal types. For Linux opera
1 min read
Node.js console.count() MethodThe console.count() method is an inbuilt application programming interface of the console module which is used to count label passed to it as a parameter, by maintaining an internal counter for that specific label. Syntax: console.count(label) Parameters: This method has one parameter as mentioned a
2 min read
Node.js console.countReset() MethodThe console.countReset() method is an inbuilt application programming interface of the console module which is used to reset the count for the specific label passed to it as a parameter. Syntax: console.countReset( label ); Parameters: This method has one parameter as mentioned above and described b
2 min read
Node.js console.debug() MethodThe console.debug() method is an inbuilt application programming interface of the console module which is used to print messages to stdout in a newline. Similar to the console.log() method. Syntax: console.debug(data, args); Parameters: This method has two parameters as mentioned above and described
2 min read
Node.js console.dir() MethodThe console.dir() method is used to get the list of object properties of a specified object. These object properties also have child objects, from which you can inspect for further information. Syntax: console.dir( object ) Parameters: This method accepts single parameter which holds the object elem
1 min read
Node.js console.error() FunctionThe console.error() function from the console class of Node.js is used to display an error message on the console. It prints to stderr with a newline. Syntax:Â console.error([data][, ...args]) Parameter: This function can contain multiple parameters. The first parameter is used for the primary messa
1 min read
Node.js console.info() MethodThe console.info() method is an inbuilt application programming interface of the console module which is used to print messages to stdout in a newline. It is similar to the console.log() method. Syntax: console.info(data, args); Parameters: This method has two parameters as mentioned above and descr
2 min read
Node.js Console Complete ReferenceThe console module in Node.js provides a set of functions to output information to the terminal or command line, helping with debugging and logging. It is a built-in utility that is essential for monitoring and troubleshooting Node.js applications.It is a global object that provides a simple debuggi
4 min read
Node.js Crypto Module
Node.js cipher.final() MethodThe cipher.final() method in Node.js is used to signal to the cipher object that the encryption or decryption process is complete. This method must be called after all data has been passed to the cipher object using the cipher.update() method. The cipher.final() method returns the remaining encrypte
2 min read
Node.js cipher.update() MethodThe cipher.update() method is an inbuilt application programming interface of class Cipher within crypto module which is used to update the cipher with data according to the given encoding format. Syntax: const cipher.update(data[, inputEncoding][, outputEncoding]) Parameters: This method takes the
2 min read
Node.js crypto.getCiphers() MethodThe crypto.getCiphers() method returns an array the names of all the supported cipher algorithms. Syntax: crypto.getCiphers() Parameters: This method doesn't accepts any parameters. Return Value: It returns the names of all the supported cipher algorithms. Below example illustrate the use of crypto.
2 min read
Node.js crypto.createDecipheriv() MethodThe crypto.createDecipheriv() method is an inbuilt application programming interface of crypto module which is used to create a Decipher object, with the stated algorithm, key and initialization vector i.e, (iv). Syntax: crypto.createDecipheriv( algorithm, key, iv, options ) Parameters: This method
3 min read
Node crypto.createCipheriv() MethodThe crypto.createCipheriv() method is an inbuilt application programming interface of the crypto module which is used to create a Cipher object, with the stated algorithm, key, and initialization vector (iv).Syntax: crypto.createCipheriv( algorithm, key, iv, options )Parameters: This method accepts
2 min read
Node.js crypto.getDiffieHellman() MethodThe crypto.getDiffieHellman() method is used to create a predefined DiffieHellmanGroup key exchange object. Here, the favored groups are 'modp1', 'modp2', 'modp5', which are defined in RFC 2412 and 'modp14', 'modp15', 'modp16', 'modp17', 'modp18', defined in RFC 3526. Syntax: crypto.getDiffieHellman
2 min read
Node.js crypto.pbkdf2() MethodThe crypto.pbkdf2() method gives an asynchronous Password-Based Key Derivation Function 2 i.e. (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iter
2 min read
Node crypto.createHash() MethodThe crypto.createHash() method is used to create a Hash object that can be used to create hash digests by using the stated algorithm. Syntax:crypto.createHash( algorithm, options )Parameters: This method accepts two parameters as mentioned above and described below:algorithm: It is dependent on the
2 min read
Node.js crypto.createHmac() MethodThe crypto.createHmac() method is used to create an Hmac object that uses the stated 'algorithm' and 'key'.Syntax:crypto.createHmac( algorithm, key, options )Parameters: This method accepts three parameters as mentioned above and described below:algorithm: It is dependent on the accessible algorithm
2 min read
Node.js Crypto Complete ReferenceNode.js crypto module handles cryptographic functionality. Cryptography is an important aspect when we deal with network security. âCryptoâ means secret or hidden. Cryptography is the science of secret writing with the intention of keeping the data secret. Example: JavaScript <script> // Node.
5 min read
Node.js DNS Module
Node.js DNSNode.js DNS (Domain Name System) module provides methods for performing DNS lookups and working with domain names. It allows you to resolve domain names into IP addresses and vice versa, which is essential for network communications and server management.DNS Module in Node.jsThe DNS module in Node.j
3 min read
Node.js dns.getServers() MethodThe dns.getServers() method is an inbuilt application programming interface of the dns module which is used to get IP addresses of the current server.Syntax:Â Â dns.getServers() Parameters: This method does not accept any parameters.Return: This method returns an array of IP addresses in RFC 5952 for
1 min read
Node.js dns.lookup() MethodThe dns.lookup() method is an inbuilt application programming interface of the dns module which is used to resolve IP addresses of the specified hostname for given parameters into the first found A (IPv4) or AAAA (IPv6) record. Syntax:dns.lookup( hostname, options, callback )Parameters: This method
3 min read
Node.js dns.lookupService() MethodThe dns.lookupService() method is an inbuilt application programming interface of the dns module which is used to resolve the addresses and port number to hostname using operating system's underlying getnameinfo implementation. Syntax: dns.lookupService( address, port, callback ) Parameters: This me
2 min read
Node.js dns.resolve() MethodThe dns.resolve() method is an inbuilt application programming interface of the dns module which is used to resolve hostname into an array of the resource records. Syntax:dns.resolve( hostname, rrtype, callback )Parameters: This method accept three parameters as mentioned above and described below:
3 min read
Node.js dns.resolve4() MethodThe dns.resolve4() method is an inbuilt application programming interface of the dns module which is used to resolve IPv4 address ('A' record) for the specified hostname using DNS protocol. Syntax:dns.resolve4( hostname, options, callback )Parameters: This method accept three parameters as mentioned
2 min read
Node.js dns.resolve6() MethodThe dns.resolve6() method is an inbuilt application programming interface of the dns module which is used to resolve IPv6 address ('AAAA' record) for the specified hostname using DNS protocol. Syntax: dns.resolve6( hostname, options, callback ) Parameters: This method accept three parameters as ment
2 min read
Node.js dns.resolveAny() MethodThe dns.resolveAny() method is an inbuilt application programming interface of the dns module which is used to resolve all records (i.e. 'ANY' or '*') for the specified hostname using DNS protocol. Syntax: dns.resolveAny( hostname, callback ) Parameters: This method has two parameters as mentioned a
2 min read
Node.js dns.resolveCname() MethodThe dns.resolveCname() method is an inbuilt application programming interface of the dns module which is used to resolve CNAME records for the specified hostname using DNS protocol. Syntax: dns.resolveCname( hostname, callback ) Parameters: This method has two parameters as mentioned above and descr
2 min read
Node.js DNS Complete ReferenceNode.js DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup.Example:JavaScript<script> // Node.js program to demonstrate the // dns.resolve() method // Accessing dns module const dns = require('dns'); //
3 min read
Node.js File System Module
Node.js File SystemThe fs (File System) module in Node.js provides an API for interacting with the file system. It allows you to perform operations such as reading, writing, updating, and deleting files and directories, which are essential for server-side applications and scripts.Table of ContentNode.js file systemKey
9 min read
Node JS fs.readFile() MethodâIn Node.js, the fs.readFile() method is a fundamental tool for reading files asynchronously, allowing your application to remain responsive while accessing file data. This method is part of Node.js's File System (fs) module, which provides an API for interacting with the file system.Syntaxfs.readFi
3 min read
Node.js fs.exists() MethodThe fs exists method in node is used to check if the input file or the directory exists or not. It is an inbuilt application programming interface of fs module which provides an API for interacting with the file system in a manner closely modeled around POSIX functions. Syntax:fs.exists( path, callb
2 min read
Node fs.existsSync() MethodIn Node.js, the fs.existsSync() method checks if a file or folder exists at a given path. It's synchronous, meaning it pauses the program until it finds the result (either true if it exists, or false if it doesn't). Because it stops everything while it works, itâs best used for quick checks in small
3 min read
Node fs.mkdir() MethodThe fs.mkdir() method in Node.js is used to create a directory asynchronously.Syntaxfs.mkdir(path, mode, callback)Parameters: This method accepts three parameters as mentioned above and described below: path: This parameter holds the path of the directory that has to be created.mode: This parameter
2 min read
Node.js fs.truncate() MethodThe fs.truncate() method in node.js is used to change the size of the file i.e either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file's current length, the file is truncated to that length. If i
2 min read
Node.js fs.renameSync() MethodIn Node.js, the fs.renameSync() method is part of the built-in File System (fs) module and is used to rename or move files and directories synchronously. This method is useful when you need to quickly change a file's name or move it to a different directory synchronously. It blocks the execution of
3 min read
Node.js fs.rmdir() MethodThe fs.rmdir() method is used to delete a directory at the given path. It can also be used recursively to remove nested directories.Syntax: fs.rmdir( path, options, callback )Parameters: This method accepts three parameters as mentioned above and described below: path: It holds the path of the direc
3 min read
Node.js fs.stat() MethodThe fs.stat() method is used to return information about the given file or directory. It returns an fs.Stat object which has several properties and methods to get details about the file or directory. Syntax:fs.stat( path, options, callback )Parameters: This method accept three parameters as mentione
3 min read
Node.js File System Complete ReferenceNode.js File System module is used to handle file operations like creating, reading, deleting, etc. Node.js provides an inbuilt module called FS (File System). Node.js gives the functionality of file I/O by providing wrappers around the standard POSIX functions. All file system operations can have s
15+ min read
Node.js Globals
Node.js HTTP Module