Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to npm run "my command" and use that parameter in my functions

Consider app.js

const { doCoolStuff } = require("./api/myApi");
// grab param from command line into "myParam"


doCoolStuff(myParam);

... // more code 

And Package.json:

{
  "name": "-------",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "send": "node app.js"
  },
  
  ... 
}

How can we pass parameter to app.js when running npm run send ?

Something like npm run send [email protected]

like image 714
JAN Avatar asked Dec 27 '25 15:12

JAN


2 Answers

Npm will parse any argument you pass to the script unless it's passed after -- followed by a space. After npm parses them, they'll be available under npm_config_ in the environment variables.

{
      "scripts": {
        "send": "echo \"send email to $npm_config_name @ $npm_config_mail "
      }
    }

Then run

npm run send --mail=xyz.com --name=sample

output: send email to [email protected]

like image 159
Sanmitra Nagaraj Avatar answered Dec 30 '25 16:12

Sanmitra Nagaraj


const params = process.argv.slice(2)

Now this param variable has all the parameters passed with the npm run command.

npm run send [email protected]

params[0] // this will provide you with the value [email protected]
like image 32
Tauseef Ahmad Avatar answered Dec 30 '25 16:12

Tauseef Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!