npm script with arguments

13 Jan 2016

npm is a powerful scripting tool to build your projects. It unifies all commands and let you do npm start, npm stop, npm run <script> etc., where the actual commands executed by them are defined under package.json.

Recently I've had the need to set some environment variables while doing npm start. npm commands allows you to pass arguments or set the env vars in several ways, but I wasn't quite satisfied:

My use case was to start my bots of different names, say:

I fiddled with npm and bash for hours and got it figured out. Basically we use the commands above, internally these would happen:

Below is my snippet from package.json:

"scripts": {
    "start": "npm run deploy",
    "deploy": "if [ $npm_config_bot ]; then bot=$npm_config_bot; echo Bot is SET to: $bot; else bot=peppurr; echo Bot is DEFAULTED to $bot; fi; DEPLOY=.keys-$bot forever start --uid $bot index.js"

Beware that if the command is split into separate npm scripts, due to the local scoping you'd actually lose the $bot variable. That's why deploy is such a long command.