How to Run npm Script in Node.js: Simple Guide
To run an
npm script in Node.js, use the command npm run script-name in your terminal, where script-name is defined in your package.json under scripts. This runs the specified script using Node.js environment.Syntax
The basic syntax to run an npm script is:
npm run <script-name>: Runs the script namedscript-namedefined inpackage.json.npm start: Runs thestartscript without needingrun.npm test: Runs thetestscript similarly.
You must be in the project folder where package.json is located.
bash
npm run script-name
Example
This example shows how to define and run a simple npm script that prints a message using Node.js.
json
{
"name": "example-project",
"version": "1.0.0",
"scripts": {
"hello": "node -e \"console.log('Hello from npm script!')\""
}
}
# To run the script, use:
npm run helloOutput
Hello from npm script!
Common Pitfalls
Common mistakes when running npm scripts include:
- Trying to run a script not defined in
package.json. - Using
npm runwithstartortestscripts unnecessarily (you can just usenpm startornpm test). - Running the command outside the project folder without
package.json. - Not escaping quotes properly in scripts that use inline Node.js commands.
bash
Wrong: npm run nonexistent Right: npm run hello
Quick Reference
| Command | Description |
|---|---|
| npm run | Run a custom script defined in package.json |
| npm start | Run the start script (shortcut for npm run start) |
| npm test | Run the test script (shortcut for npm run test) |
| npm run | List all available scripts in package.json |
Key Takeaways
Use
npm run script-name to run scripts defined in package.json.You can run
start and test scripts with shortcuts npm start and npm test.Always run npm scripts from the folder containing your package.json file.
Check your package.json scripts section to confirm script names and commands.
Escape quotes properly when using inline Node.js commands in scripts.