How do I add a custom script to my package.json file that runs a javascript file?

Jake.JS picture Jake.JS · Apr 5, 2016 · Viewed 177.7k times · Source

I want to be able to execute the command script1 in a project directory that will run node script1.js.

script1.js is a file in the same directory. The command needs to be specific to the project directory, meaning that if I send someone else the project folder, they will be able to run the same command.

So far I've tried adding:

"scripts": {
    "script1": "node script1.js"
}

to my package.json file but when I try running script1 I get the following output:

zsh: command not found: script1

Does anyone know the steps necessary to add the script mentioned above to the project folder?

*Note: the command can not be added to the bash profile (cannot be a machine specific command)

Please let me know if you need any clarification.

Answer

wesleysmyth picture wesleysmyth · Jan 27, 2017

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.