0

I'm creating a small personal server that I want to post data to from the web console. I am confident that I will forget what I need to do so I wrote this:

"scripts": {
    "console": "node console.js",
    "server": "json-server -w db.json -p 5001",
    "start": "npm run console && npm run server",
    "write": "node server.js"
  }

When I run npm start I'll get my front end script consoled which I then copy-paste.

I would like to be able to pass a variable to the console.js, so I tried npm start myVarHere but I don't know how to read that in console.js

If I run npm run console myVarHere, then I can get that with process.argv[2] but is there a way to do it the way I want?

relidon
  • 2,142
  • 4
  • 21
  • 37
  • Duplicate question [Sending command line arguments to npm script](https://stackoverflow.com/questions/11580961/sending-command-line-arguments-to-npm-script) – Num Lock Aug 18 '20 at 05:30
  • 1
    If you're running your npm scripts on *Nix then you can utilize a shell function, For instance change your `start` script in _package.json_ to the following: `"start": "func() { npm run console \"$1\" && npm run server; }; func"` (as per Solution 1 in the answer at the link I provided). However, for cross-platform, you'll need to utilize a _node.js_ script to handle this (as per Solution 2 in the answer at the link I provided)). To run your script via the command line you'll need to run: `npm start -- myVarHere` – RobC Aug 18 '20 at 06:53
  • @RobC yes!!! Solution 2 worked (solution one did not). Thank you. I didn't know you could do that, this actually removes the need for the first console script. Away, thanks a lot. Convert it to an answer if you wish. That's cool :) – relidon Aug 18 '20 at 14:11
  • That's good news. Solution one probably didn't work because you're using windows and npm utilizes CMD as the default shell to run npm scripts. On *nix npm utilizes `sh` as the default shell. – RobC Aug 18 '20 at 14:15
  • @RobC absolutely – relidon Aug 18 '20 at 17:55
  • @RobC last thing, is there a way to check if `$1` is set inside that `func`. to check if user gave a variable `npm start someVar`. I tried variables of shell if statements but nothing. (totally of topic I know) – relidon Aug 20 '20 at 06:46
  • 1
    @relidon - you can do either **A:** `"start": "func() { if [[ -n \"$1\" ]]; then npm run console \"$1\" && npm run server; else echo \"Missing argument\"; fi; }; func",` - which would log _"Missing argument"_ to the console when someone just ran `npm start`, (ie. without passing an argument). Or when running e.g. `npm start -- someVar` (ie. with an argument) the script would run. **B)** Or `"start": "func() { npm run console \"${1:-quux}\" && npm run server; }; func",` - which when running `npm start` (without an argument) would use `quux` as the default argument to pass to `npm run console`. – RobC Aug 20 '20 at 07:20

0 Answers0