Node.js NPM Scripts

Node.js – NPM Scripts

NPM Scripts allow you to run commands defined inside your package.json file.
They help automate tasks like:

  • Running server

  • Starting development mode

  • Running tests

  • Compiling code

  • Cleaning files

  • Building projects

Scripts make your workflow faster and more organized.


1. Where Are NPM Scripts Defined?

In your package.json file:



 


2. How to Run NPM Scripts

Use the command:

npm run script-name

Example:

npm run dev

But for one special script:

Default Script — start

npm start

(You don’t need to type run for the start script.)


3. Common Useful NPM Scripts

1. Start the application



 

Run:

npm start

2. Development Mode (with Nodemon)

"dev": "nodemon server.js"

Run:

npm run dev

3. Clean build folder



 

Run:

npm run clean

4. Build project



 

Run:

npm run build"

5. Run tests



 

Run:

npm test

4. Using Multiple Commands in Scripts

Run two commands sequentially

"start": "node server.js && echo Server Started"

Run two commands in parallel

(For Linux/Mac)

"dev": "npm run watch & npm run serve"

(For Windows use concurrently package)


5. Passing Arguments to Scripts

"greet": "node greet.js"

Run with arguments:

npm run greet -- Vipul

Inside Node.js:

console.log(process.argv);

6. Pre and Post Scripts

NPM automatically runs scripts with prefixes:

prestart → runs before start

poststart → runs after start

Example:



 

Run:

npm start

Order:

Before Start
App running...
After Start

7. Defining Custom Scripts

You can create any script name:



 

Run:

npm run hello
npm run deploy

8. View All Available Scripts

npm run

This shows all scripts inside package.json.


🎯 Summary

Feature Description
Run tasks Build, start, test, clean, etc.
Automated workflows Saves time
Custom commands Flexible and powerful
Supports pre/post hooks Advanced control
Integrates with tools nodemon, webpack, jest, ESLint

You may also like...