使用 nodejs 执行 shell 个脚本命令

executing shell script commands using nodejs

我正在尝试寻找一些好的库来使用 nodejs 执行 shell 脚本命令(例如:rm、cp、mkdir 等...)。最近没有关于可能的包的明确文章。我读了很多关于 exec-sync 的文章。但有人说它已被弃用。真的,我迷路了,什么也找不到。我尝试安装 exec-sync,但收到以下错误:

npm ERR! ffi@1.2.5 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!  
npm ERR! Failed at the ffi@1.2.5 install script 'node-gyp rebuild'.

你有什么建议吗?

您可以简单地使用节点子进程核心模块,或者至少使用它来构建您自己的模块。

Child Process

The child_process module provides the ability to spawn child processes in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() function:

特别是 exec() 方法。

child_process.exec()

spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

这里是文档中的示例。

Spawns a shell then executes the command within that shell, buffering any generated output.

const exec = require('child_process').exec;
exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});