Javascript 如何在nodejs中执行顺序基本命令?
我需要在nodejs中按顺序运行4个bash命令Javascript 如何在nodejs中执行顺序基本命令?,javascript,node.js,npm,npm-scripts,Javascript,Node.js,Npm,Npm Scripts,我需要在nodejs中按顺序运行4个bash命令 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 如何做到这一点?或者是否可以添加npm脚本?要从节点运行shell命令
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
如何做到这一点?或者是否可以添加npm脚本?要从节点运行shell命令,请使用
exec
,
三种可能的方法是
exec
从节点运行它exec
从节点分别运行每个命令promisify
exec
()并使用async/await
而不是回调。
比如说,
const {promisify} = require('util');
const {exec} = require('child_process');
const execAsync = promisify(exec);
(async () => {
const {stdout, stderr} = await execAsync('set +o history');
...
})();
要扩展@melc的答案,并按顺序执行请求,您可以执行以下操作:
const {promisify} = require('util');
const {exec} = require('child_process');
const execAsync = promisify(exec);
const sequentialExecution = async (...commands) => {
if (commands.length === 0) {
return 0;
}
const {stderr} = await execAsync(commands.shift());
if (stderr) {
throw stderr;
}
return sequentialExecution(...commands);
}
// Will execute the commands 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",
);
或者,如果您不关心stdout/sterr,则可以使用以下一个衬里:
const commands = [
"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 commands.reduce((p, c) => p.then(() => execAsync(c)), Promise.resolve());
您可以运行包含这些命令的shell脚本,也可以在nodejs程序中单独运行它们。请参阅.What does+o do?@slebetman以执行具有特殊字符的SED命令
set+o history
required To set。