0
0
NodejsHow-ToBeginner · 3 min read

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 named script-name defined in package.json.
  • npm start: Runs the start script without needing run.
  • npm test: Runs the test script 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 hello
Output
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 run with start or test scripts unnecessarily (you can just use npm start or npm 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

CommandDescription
npm run Run a custom script defined in package.json
npm startRun the start script (shortcut for npm run start)
npm testRun the test script (shortcut for npm run test)
npm runList 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.