【问题标题】:executing shell script commands using nodejs使用 nodejs 执行 shell 脚本命令
【发布时间】:2017-01-13 15:36:52
【问题描述】:

我正在尝试找到一些好的库来使用 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'.

你有什么建议吗?

【问题讨论】:

标签: javascript node.js shell exec rm


【解决方案1】:

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

Child Process

child_process 模块提供了以与 popen(3) 类似但不相同的方式生成子进程的能力。此功能主要由 child_process.spawn() 函数提供:

尤其是exec() 方法。

child_process.exec()

生成一个 shell 并在该 shell 中运行一个命令,完成后将 stdout 和 stderr 传递给回调函数。

这里是文档中的示例。

生成一个 shell,然后在该 shell 中执行命令,缓冲任何生成的输出。

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}`);
});

【讨论】:

  • 有同步版本的exec吗?
  • 他在问如何运行一个shell脚本,你展示如何运行一个命令。