How to use params in NPM scripts

Let's see how to use params in NPM scripts that you setup in your package.json and how to read this variables in your scripts

🛠 Setup in package.json

In order to run a script with a command like npm run myscript you should add the next line in the scripts block of your package.json:

"scripts": {
  "myscript": "./bin/myscript.js run=true"
}

👨‍💻 How to read params

In the ./bin/myscript.js file, you can read the params with process.argv that contains:

 [ 
  "node",  
  "/Users/dburgos/code/npm-params/bin/myscript.js",
  "run=true"
 ]

So you can access it as following:

const parameter = process.argv[2]; // "run=true"
const runValue = parameter.split('=')[1]; // "true"

💡 Please note you will get them as strings

Another example 👇

If you set a parameter like --delete true:

"scripts": {
  "myscript": "./bin/myscript.js --delete true"
}

⚠️ Note the space between both.

You will get them as following:

 [ 
  "node",  
  "/Users/dburgos/code/npm-params/bin/myscript.js",
  "--delete",
  "true",
 ]

Then you will get:

const parameter = process.argv[2]; // "--delete"
const value = process.argv[3]; // "true"

Leave comment with your questions or doubts, happy yo help you 🙂
👋 Thanks for reading!

David Burgos

Read more posts by this author.