NPM Scripts in Node.js
NPM scripts allow developers to define and execute commands from the scripts section of package.json. They help simplify common development tasks such as starting an application, running tests, checking code, and building a project.
Instead of typing long commands repeatedly, developers can create short, meaningful script names and execute them through NPM.
1. What Are NPM Scripts?
NPM scripts are commands defined inside the
"scripts" property of the package.json
file. They provide a convenient way to run commands associated
with a project.
For example, we can define a script named start
that executes node app.js. Instead of typing the
complete command every time, we can run npm start.
Example: package.json
{
"name": "studentapp",
"version": "1.0.0",
"scripts": {
"start": "node app.js"
}
}
Here, start is the script name and
node app.js is the command that NPM executes.
Contains the scripts property
npm start
The application starts
2. Why Do We Use NPM Scripts?
NPM scripts are useful for the following reasons:
- Run an application using a short command.
- Start a development server.
- Run automated tests.
- Check and format source code.
- Build an application before deployment.
- Standardize commands across a development team.
node app.js, a script named
start lets you execute the same command using
npm start.
3. Create a Node.js Project
Let's create a simple project to understand NPM scripts.
Step 1: Create a folder
mkdir NpmScriptsDemo
cd NpmScriptsDemo
Step 2: Initialize NPM
npm init -y
This creates a default package.json file in the
project directory.
Step 3: Create app.js
console.log("Welcome to NPM Scripts!");
console.log("Student Management Application Started.");
Project structure
NpmScriptsDemo/
|
|-- app.js
|
|-- package.json
4. Create Your First NPM Script
Open package.json and add a
start script inside the existing scripts object.
{
"name": "npmscriptsdemo",
"version": "1.0.0",
"scripts": {
"start": "node app.js"
}
}
If your package.json contains additional properties, keep them.
Add the start entry to its existing scripts object.
Run the script
npm start
Expected output:
Welcome to NPM Scripts!
Student Management Application Started.
NPM executes the command defined by the
start script. In this example, it runs
node app.js.
5. Understanding Common NPM Script Commands
| Script Command | Purpose |
|---|---|
npm start |
Runs the start script. |
npm test |
Runs the test script. |
npm run dev |
Runs a custom script named dev. |
npm run build |
Runs a custom script named build. |
npm run lint |
Runs a custom script named lint. |
npm run script-name. The start and
test scripts have convenient shorthand commands.
Each script must be defined before it can run.
6. Create Multiple NPM Scripts
A project can define several scripts for different development tasks.
Example package.json
{
"name": "npmscriptsdemo",
"version": "1.0.0",
"scripts": {
"start": "node app.js",
"dev": "node app.js",
"test": "node test.js",
"info": "node info.js"
}
}
These scripts execute different JavaScript files. Create each file before running its corresponding script.
Example: test.js
console.log("Test script executed successfully.");
Run the test script
npm test
Expected output:
Test script executed successfully.
This example only prints a message; it does not run a real automated test framework. A real test script normally executes a testing tool or test program.
7. Use Nodemon with NPM Scripts
Nodemon is a development tool that restarts a Node.js application
when watched files change. We can create a
dev script to run Nodemon conveniently.
Step 1: Install Nodemon
npm install nodemon --save-dev
Step 2: Add the dev script
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
Add these entries to your existing scripts object. Do not create a duplicate scripts property.
Step 3: Run development mode
npm run dev
Expected application message:
Welcome to NPM Scripts!
Student Management Application Started.
Nodemon may display additional startup messages in the terminal.
When you edit a watched file, it restarts the application.
Press Ctrl + C to stop the process.
8. Pass Arguments to NPM Scripts
NPM scripts can accept arguments. When passing additional
arguments to a script, use -- to separate the
NPM options from the arguments intended for the script.
Example package.json
{
"scripts": {
"greet": "node greet.js"
}
}
Create greet.js
const name = process.argv[2] || "Student";
console.log(`Hello, ${name}!`);
Run the script with an argument
npm run greet -- Samadhan
Expected output:
Hello, Samadhan!
Here, process.argv[2] contains the first
application argument, which is Samadhan.
9. Pre and Post Scripts
NPM supports lifecycle scripts that can run before or after
certain scripts. For a custom script named
build, you can define prebuild
and postbuild.
Example package.json
{
"scripts": {
"prebuild": "node prebuild.js",
"build": "node build.js",
"postbuild": "node postbuild.js"
}
}
Create each of the three JavaScript files and add a
console.log() statement to each one.
Example: prebuild.js
console.log("Preparing the project...");
Example: build.js
console.log("Building the project...");
Example: postbuild.js
console.log("Build process finished.");
Run the build script
npm run build
Expected output:
Preparing the project...
Building the project...
Build process finished.
For custom scripts, NPM runs the matching pre-script before the main script and the matching post-script after it, provided the earlier command succeeds. These examples demonstrate the execution order; they do not perform a real build.
10. Useful NPM Script Commands
| Command | Purpose |
|---|---|
npm start |
Runs the start script. |
npm test |
Runs the test script. |
npm run dev |
Runs the custom dev script. |
npm run build |
Runs the build script. |
npm run |
Lists the available scripts in the project. |
npm run greet -- Samadhan |
Passes an argument to the greet script. |
11. Common NPM Script Errors
| Error | Reason | Solution |
|---|---|---|
| Missing script | The requested script is not defined. | Add the script to package.json. |
| Cannot find module | The JavaScript file or package is missing. | Check the file path and install required packages. |
| Invalid package.json | JSON syntax is incorrect. | Check commas, quotes, braces, and brackets. |
| Command not found | The required executable may not be installed or available. | Install the tool in the project and check the script. |
| Port already in use | Another process is using the required port. | Stop the other process or choose another port. |
12. Practice Tasks
- Create a project named EmployeeApp.
- Create a start script to run app.js.
- Create a dev script using Nodemon.
- Create a test script that prints a message.
- Create a greet script that accepts a name.
- Create prebuild, build, and postbuild scripts.
- Run all scripts from the terminal.
- Use
npm runto display available scripts.
Summary
NPM scripts are commands defined in the scripts property of package.json. They help developers start applications, run tests, execute development tools, and automate common tasks. The npm start and npm test commands provide convenient shortcuts, while custom scripts are executed with npm run. Arguments can be passed to scripts, and prebuild and postbuild scripts can run before and after a custom build script. Understanding NPM scripts helps developers manage and automate Node.js projects efficiently at CIIT TRAINING INSTITUTE.