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:
Example:
But for one special script:
Default Script — start
(You don’t need to type run for the start script.)
✅ 3. Common Useful NPM Scripts
1. Start the application
Run:
2. Development Mode (with Nodemon)
Run:
3. Clean build folder
Run:
4. Build project
Run:
5. Run tests
Run:
✅ 4. Using Multiple Commands in Scripts
Run two commands sequentially
Run two commands in parallel
(For Linux/Mac)
(For Windows use concurrently package)
✅ 5. Passing Arguments to Scripts
Run with arguments:
Inside Node.js:
✅ 6. Pre and Post Scripts
NPM automatically runs scripts with prefixes:
prestart → runs before start
poststart → runs after start
Example:
Run:
Order:
✅ 7. Defining Custom Scripts
You can create any script name:
Run:
✅ 8. View All Available Scripts
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 |
