[英]How to execute sequential base commands in nodejs?
我需要在 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 命令, 請使用exec
, https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
三種可能的方法是,
創建一個包含所有所需命令的 bash 腳本文件,然后使用exec
從節點運行它。
使用exec
從節點單獨運行每個命令。
使用 npm 包,例如以下之一(我沒有嘗試過) https://www.npmjs.com/package/shelljs
https://www.npmjs.com/package/exec-sh
也可以promisify
exec
( https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original ) 並使用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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.