I need to run 4 bash mands sequentially in nodejs.
set +o history
sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js
sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map
set -o history
how this could be achieved? or is it possible to add in npm script?
I need to run 4 bash mands sequentially in nodejs.
set +o history
sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js
sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map
set -o history
how this could be achieved? or is it possible to add in npm script?
Share Improve this question asked Dec 2, 2019 at 7:09 Ajarudin GungaAjarudin Gunga 4535 silver badges24 bronze badges 3- You can either run a shell script that contains those mands or you can run them individually from within a nodejs program. See the child_process module. – jfriend00 Commented Dec 2, 2019 at 7:18
- What does +o do? – slebetman Commented Dec 2, 2019 at 7:20
-
@slebetman To execute SED mands with special chars
set +o history
required to set. stackoverflow./a/59133341/7566696 – Ajarudin Gunga Commented Dec 2, 2019 at 7:22
2 Answers
Reset to default 4To extend @melc's answer, to execute the requests sequentially, you can do:
const {promisify} = require('util');
const {exec} = require('child_process');
const execAsync = promisify(exec);
const sequentialExecution = async (...mands) => {
if (mands.length === 0) {
return 0;
}
const {stderr} = await execAsync(mands.shift());
if (stderr) {
throw stderr;
}
return sequentialExecution(...mands);
}
// Will execute the mands in series
sequentialExecution(
"set +o history",
"sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js",
"sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map",
"set -o history",
);
Or if you don't care about stdout/sterr, you can use the following one-liner:
const mands = [
"set +o history",
"sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js",
"sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map",
"set -o history",
];
await mands.reduce((p, c) => p.then(() => execAsync(c)), Promise.resolve());
To run shell mands from node use exec
,
https://nodejs/api/child_process.html#child_process_child_process_exec_mand_options_callback
Three possible approaches could be,
Create a bash script file containing all needed mands and then run it from node using
exec
.Run each mand individually from node using
exec
.Use an npm package, for example one of the following (I haven't tried them) https://www.npmjs./package/shelljs
https://www.npmjs./package/exec-sh
It's also possible to promisify
exec
(https://nodejs/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original) and use async/await
instead of callbacks.
For example,
const {promisify} = require('util');
const {exec} = require('child_process');
const execAsync = promisify(exec);
(async () => {
const {stdout, stderr} = await execAsync('set +o history');
...
})();