Is it possible and how to run a batch script in npm command?
I have an angular project, in package.json
file, under scripts
section, I want to define a npm command to run batch script. I know I can run shell script with keyword bash
e.g.
"start": "cd mydir && bash ./myscript"
Then I can run npm start
in my project directory, which will change directory and execute myscript.sh
script. What is the equivalent keyword to run batch script in npm?
Newbie here. Sorry if this is a duplicate question; maybe I'm not search the correct terms, but I can't see to find answers to this question.
To help provide context to this answer, let's say we two batch files named say-hello.bat
and say-hello-cmd
. Both batch files have the same simple contrived content as follows:
echo Hello World
When invoking either of the two batch files via npm-scripts
, we expect the console to log:
Hello World
Project Directory Structure:
Now, let's assume our project directory is structured as follows:
.
├── a
│ └── b
│ ├── say-hello.bat
│ └── say-hello.cmd
├── package.json
├── say-hello.bat
├── say-hello.cmd
└── ...
As you can see, we have:
say-hello.bat
and say-hello.cmd
stored in the root of the project directory. They're at the same level as package.json
.say-hello.bat
and say-hello.cmd
stored in a sub directory of the project directory The path to these is: a/b/
npm-scripts
To be able to invoke these batch files via npm
, the scripts
section of package.json
should be defined something like the following:
{
...
"scripts": {
"bat": "say-hello.bat",
"cmd": "say-hello.cmd",
"bat-in-sub-dir": "cd a/b/ && say-hello.bat",
"cmd-in-sub-dir": "cd a/b/ && say-hello.cmd"
},
...
}
If you now cd
to your project directory and run any of the following commands:
npm run bat
npm run cmd
npm run bat-in-sub-dir
npm run cmd-in-sub-dir
The batch file(s) will be run and you will successfully see the words Hello World
logged to the console.
Notes
The notable difference between these examples above is:
When the batch file is stored in the root of your projects directory you just provide the name of the batch file in your script. E.g.
"bat": "say-hello.bat"
When the batch file is stored in a sub directory of your project directory (e.g. a/b/
) you have to firstly cd
to that folder, and then provide the name of the batch file to run. E.g.
"bat-in-sub-dir": "cd a/b/ && say-hello.bat"