npm is an awesome tool built directly inside of Node.js. You can use it to configure and run common scripts like running your unit tests or starting your webserver.

npm has 4 default npm-scripts commands:

  • test
  • start
  • stop
  • restart

We will look into all these and see how to create custom commands.

1) Getting started:

Let’s start with an empty project folder, cd into it and run npm init. Pick a name for your project and use the defaults for the remaining fields.

Your package.json should look something like:

{
"name": "npm-scripts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Klughertz Jonathan (http://klugjo.github.io/)",
"license": "ISC"
}

2) npm test:

The default package.json comes with a scripts object and a test command:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

Our npm-test command is already good to go.

To run an npm script:

npm run-script <command> [-- <args>...]

alias: npm run

Back to your terminal, type npm run-script test or npm run test to run the test command.

At the moment it will return an error so remove the exit 1 portion of the script to make it work:

"test": "echo \"Error: no test specified\""

Hint:

Typing npm run-script test is a bit lengthy. Fortunately, there are shortcuts built into NPM.

You can use any of the following commands, they are all equivalent:

  • npm run-script test
  • npm run test
  • npm test
  • npm tst
  • npm t

In a real world project, you would use that command to run your unit test script command. By setting the test command to mocha test for example.

3) npm start and stop:

The npm-start and npm-stop commands work the same way as the npm-test command. They are typically used to start and stop the application.

Edit your package.json to include the start and stop commands:

"scripts": {
"test": "echo \"Error: no test specified\"",
"start": "echo \"Error: no start command specified\"",
"stop": "echo \"Error: no stop command specified\""
},

As before, you can use npm run start or the shorter versions:

  • npm start
  • npm stop

4) npm restart:

If no restart command is specified, the npm-restart runs a package’s “stop” and “start” consecutively.

At the moment if you run npm restart, you will get:

npm scripts jonathan$ npm restart

Error: no stop command specified

Error: no start command specified

If you add the following restart command in your package: "restart": "echo \"Error: no restart command specified\"" and run npm restart, you will get:

npm scripts jonathan$ npm restart

Error: no restart command specified

5) Custom scripts

On top of these defaults, you can of course add your own commands.

For example, add "custom": "echo \"Running custom command\"" to your package.

And run it using npm run custom.

All custom commands have to be run using the npm run <command> or npm run-script <command> syntax.

Happy scripting !