4

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.

4
  • 4
    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 to delimit end of options). Commented May 8, 2019 at 8:58
  • 2
    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. Commented May 8, 2019 at 9:05
  • 1
    This works perfectly, thanks @RobC Commented May 21, 2019 at 17:01
  • see stackoverflow.com/questions/47606901/… answer Commented Oct 20, 2021 at 15:36

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.