Dynamically pass a file name to my NPM script as a command line arg - npm-scripts

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.

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

Related

What should be NPM command for solving this question?

I tried various solutions for this question but not able to pass 2 test cases amongst 4. Please help me crackdown this problem
Perform the below mentioned steps by creating package.json file named npm_commands in the maxbot directory
Create a file named index.js.
Write a js code in index.js file to create a string named myVar and value as node package manager
and convert it into uppercase.
NOTE: Please use console.log to display the output of myVar in index.js file
Configure scripts in package.json
(a) to check the versions of npm and node by using npm run release | tee output1.txt
(b) to execute index.js by using npm run build | tee output.txt
npm init - to initialize new package
give npm_commands as package name
give index.js as start file
Create new file named as index.js
declare : let myVar = "node package manager"
print var in uppercase: console.log(myVar.toUpperCase());
Add these scripts in package.json
to check npm and node version: "release": "npm -v && node -v",
to execute index.js file: "build": "node index.js"
Save and then run these commands to get the results:
npm run release | tee output1.txt
npm run build | tee output.txt
Step 1: run the command to initialize new package
npm init
Step 2: Command will start package initialization process
Set the package name:
package name: (challange) npm_commands
Step3: Press enter till time it ask for "entry point", by default it set to index.js verify and press enter key. Until the initialization process ends.
Step 4: Go to editor project explorer add create new file index.js, and add following code in it.
let myVar = 'node package manager';
console.log(myVar.toUpperCase());
Step 5: Add following lines into script block of package.json file
"release" : "npm -v && node -v",
"build" : "node index.js",
Script block looks like as below after adding above lines
"scripts": {
"release" : "npm -v && node -v",
"build" : "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Step 6: Now open the command prompt and run the following commands
npm run release | tee output1.txt
npm run build | tee output.txt
Above commands create the output1.txt, and output.txt files in project explorer containing respective commands output.
Step 7: That's it! now run the test and check your FS_SCORE for 100% and submit the test.

npm script onchange/watch only run command on files that actually changed rather than all files in a folder

I have following npm script in the package.json:
"scripts": {
"upload:js": "onchange \"dist/js\" -- echo {{changed}} && node sp-asset-upload.js {{changed}} 3",
"start:message": "echo 'Watching for code changes. Start making changes!'",
"watch:js": "onchange -f \"add change\" \"dev/scripts/**/*.js\" -- npm-run-all clean:js buildjs:main buildjs:slick-init",
"watch:uploadjs": "npm run upload:js",
"watch": "npm-run-all start:message watch:js watch:uploadjs",
"start": "npm run watch"
}
The sp-asset-upload.js is some javascript that relies on spsave package to upload files to SharePoint.
I am interested in uploading only the files that have recently changed, rather than all files (that may or may not have changed) in the dist\js folder.
I am using the onchange package to watch for changes. I need to basically capture the files that changed and pass that as parameter to the sp-asset-upload.js file instead of doing the below:
node sp-asset-upload.ms "dist/js/*.js" 3 - where the number parameter determines whether to upload a minor copy or major version to SharePoint.
Can someone who might have done this share some insight?

How to use commander.js command through npm command

I'm using commander.js command like this ./index.js --project mono --type item --title newInvoice --comments 'Creates an invoice' --write, Now I'm using the command through npm run item newInvoice by setting some options in package.json file like this
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"snapshot": "node --max-old-space-size=10240 ./scripts/snapshot.js",
"item": "./index.js --project mono --type item --title",
"config": "./index.js --project mono --type config --title"
}
But whenever I'm trying to get the --write option with npm using npm run item newInvoice --write it's showing undefined for --write
Source Code:
#!/usr/bin/env node
const fs = require('fs');
const program = require('commander');
require('colors');
program
.version('0.1.0')
.option('--project [project]', 'Specifies the project name', 'mono')
.option('--type [type]', 'Type of code to generate, either "item" or "config"', /^(config|item)$/, 'config')
.option('--title [title]', 'Title of the item or config', 'untitled')
.option('--comments [comments]', 'Configs: describe the config', '#todo description/comments')
.option('--write', 'Write the source code to a new file in the expected path')
.option('--read', 'To see what would be written the source code to a new file in the expected path')
.parse(process.argv);
console.log(program.write, program.read); //=> undefined undefined
Can anyone help me how to use commander js command with npm?
When you run your npm run command you need to utilize the special -- option to demarcate the end of any option(s) that may belong to the npm run command itself (e.g. --silent), and the beginning of the argument(s) that are to be passed to the end of the npm script.
Run the following command instead:
npm run item -- newInvoice --write
Given the aforementioned command and the command currently defined your npm script named item they essentially form the following compound command prior to execution:
./index.js --project mono --type item --title newInvoice --write
^ ^
The npm run documentation states the following:
As of npm#2.0.0, you can use custom arguments when executing scripts. The special option -- is used by getopt to delimit the end of the options. npm will pass all the arguments after the -- directly to your script.
and it's usage syntax is defined in the Synopsis section as:
npm run-script <command> [--silent] [-- <args>...]
^^
Note: It's not possible to add the -- option to the npm script itself.

A valid environment variable to satisfy env:PRISMA_SECRET could not be found

When I try to generate a Prisma token, it keeps giving me the following error, even though I have the PRISMA_SECRET configured in config/dev.env.:
A valid environment variable to satisfy the declaration!
'env:PRISMA_SECRET' could not be found.
My config/dev.env is configured as following:
PRISMA_ENDPOINT=http://local:4466/
PRISMA_SECRET=somesecret
JWT_SECRET=somesecret
And following is how I start npm run dev:
"dev": "env-cmd ./config/dev.env nodemon src/index.js --ext js,graphql --exec babel-node",
When I console.log(process.env.PRISMA_SECRET), it shows the variable properly so I'm not sure what's going on. I'm tried restarting Docker and re-deploying Prisma, but to no avail. Any help would be appreciated.
You need to add an -f flag, it's to do with an update to env-cmd
"dev": "env-cmd -f ./config/dev.env nodemon src/index.js --exec babel-node -e js,graphql",

Passing argument to the middle of an npm script

Title says it all. I want to be able to pass the argument to the middle of an npm script so that I may do the following.
$ npm run deploy -- <destination-path>
In package.json
"scripts": {
"deploy": "robocopy dist <destination-path> /E /NP"
}
Is this possible without using environment variables or npm's configuration variables?
Per Passing args into run-scripts #5518 it would appear that is it not possible to pass arguments to the middle of the script.
We are not going to support passing args into the middle of the script, sorry. If you really need this, write your test command using literally any of the command line parsers that anyone uses. (Minimist, dashdash, nopt, and commander all support this just fine.)
However, an alternative to this using the npm configuration block has been documented here. My implementation then looks like this:
"name": "foo"
"config": { "destination" : "deploy" },
"scripts": { "deploy": "robocopy dist %npm_package_config_destination% /E /NP" }
I can then override this on the command line and on my build server with:
npm run deploy --foo:destination=C:\path\to\deploy\dir
You can use an environment variable to set the destination path.
PATH=/path/to/file npm run deploy -- $PATH
or
export PATH=/path/to/file
npm run deploy -- $PATH
I have a different way to do that via shell.
If your npm command is:
"deploy": "robocopy dist ${1} /E /NP"
Where ${1} is the parameter you want to substitute.
Then wrap it in a function as follow:
"deploy": "func() { robocopy dist ${1} /E /NP";}; func"
then you can run a positional parameter substitution in shell as follow:
npm run deploy -- xyz
which would run
robocopy dist xyz /E /NP
And since this is a shell script, you can use default parameters as well:
"deploy": "func() { robocopy dist ${1:-xyz} /E /NP";}; func"
And you can use it as follows:
npm run deploy <==> robocopy dist xyz /E /NP
npm run deploy -- abc <==> robocopy dist abc /E /NP
You can make use of the arg structure of "sh -c". In my example below, I have to echo-feed the npm arg into a language parser. The argument for npm run foma <some word> will be in place of the $0:
"sayhello": "bash -c 'echo hello $0!"
A cross-platform solution I use is:
"arg-helper": "node -e \"process.stdout.write(require('child_process').execSync(process.argv[1].replace('$', process.argv[2] || '')))\"",
"sayhello": "npm run arg-helper \"echo hello $!\"
...
>npm run sayhello world
Levereging npm_config_* variables.
package.json
{
"scripts": {
"echoMyParam": "echo 'your param value is' $npm_config_foo"
}
}
Run
npm run echoMyParam --foo=bar
Result
your param value is bar
It's important to check the docs for other cases: https://docs.npmjs.com/using-npm/config