3

Here is some code.

I have tried using -- and passing as an env variable i.e. --script=myscript.js. The code I have linked is getting me very close but I need to remove the space between the script name.

"scripts": {
    "script": "nodemon --exec babel-node ./scripts/${*}",
  }

then I run in console:

npm run script populateVehicleData.js. 

That results in this

[nodemon] 1.18.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `babel-node ./scripts/ populateVehicleData.js`
internal/modules/cjs/loader.js:657
    throw err;
    ^

Error: Cannot find module '/Users/jakeneels/work/api/scripts/'

Notice that the script is executing 'babel-node ./scripts/ populateVehicleData.js'. Why is the space there? how do I get rid of it?

I expect to execute babel-node ./scripts/populateVehicleData.js and run my script whatever its name might be. instead i get babel-node ./scripts/ populateVehicleData.js causing npm to not find the file due to the space between scripts/ and populateVehicleData.js.

halfer
  • 19,824
  • 17
  • 99
  • 186
Jake Neels
  • 31
  • 3
  • 3
    Wrap your npm script in a shell function and utilize `${1}` to reference the filename (i.e. the first positional parameter/arg) passed. For instance change your npm script to: `"script": "func() { nodemon --exec babel-node ./scripts/${1}; }; func",` - then run following command: `npm run script populateVehicleData.js.` Or run `npm run script -- populateVehicleData.js.` (Note the double hyphens `--` used in 2nd invocation, i.e. [`getopt`](https://unix.stackexchange.com/questions/147143/when-and-how-was-the-double-dash-introduced-as-an-end-of-options-delimiter) to delimit end of options). – RobC May 08 '19 at 08:58
  • 1
    You could also consider changing your script to utilize a default filename. For instance: `"script": "func() { nodemon --exec babel-node ./scripts/${1:-somefile.js}; }; func",` - Now if you run `npm run script` (i.e. without a filename argument) it will default to `./scripts/somefile.js` . However, if you run `npm run script populateVehicleData.js` it will use the file at `./scripts/populateVehicleData.js` instead. – RobC May 08 '19 at 09:05
  • 1
    This works perfectly, thanks @RobC – Jake Neels May 21 '19 at 17:01
  • see https://stackoverflow.com/questions/47606901/can-i-put-a-variable-for-a-filename-in-the-scripts-property-of-package-json answer – Hamid Taebi Oct 20 '21 at 15:36

1 Answers1

1

You can also set the file name as an env variable and read it from there.

"scripts": {
"script": "nodemon --exec babel-node ./scripts/${fileName}",
}

and then

fileName=populateVehicleData npm run script
William Neely
  • 1,923
  • 1
  • 20
  • 23