0
0
NodejsHow-ToBeginner · 3 min read

How to Create npm Script in Node.js: Simple Guide

To create an npm script in Node.js, add a script entry inside the scripts section of your package.json file. Then run it using npm run script-name in your terminal.
📐

Syntax

The scripts section in package.json holds key-value pairs where the key is the script name and the value is the command to run.

Example parts:

  • "start": the script name you will call.
  • "node app.js": the command executed when you run the script.
json
{
  "scripts": {
    "script-name": "command to run"
  }
}
💻

Example

This example shows how to create a script named start that runs a Node.js file called app.js. You run it with npm start.

json
{
  "name": "my-node-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js"
  }
}

// app.js file content:
// console.log('Hello from app.js');
Output
Hello from app.js
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to add scripts inside the scripts object.
  • Trying to run scripts without the npm run prefix (except for start which can run with just npm start).
  • Using incorrect command syntax inside the script value.

Always check your package.json syntax and use quotes properly.

json
Wrong:
{
  "scripts": {
    start: node app.js
  }
}

Right:
{
  "scripts": {
    "start": "node app.js"
  }
}
📊

Quick Reference

CommandDescription
npm run Runs the script named from package.json
npm startRuns the start script (shortcut, no run needed)
npm testRuns the test script (shortcut)
npm run buildRuns a build script if defined
npm run lintRuns a lint script if defined

Key Takeaways

Add scripts inside the scripts object in package.json using key-value pairs.
Run scripts with npm run script-name, except start and test which have shortcuts.
Always use quotes around the command string in package.json.
Check your package.json syntax carefully to avoid errors.
npm scripts help automate common tasks like starting, testing, and building your app.