使用nodejs执行shell脚本命令

executing shell script commands using nodejs

本文关键字:脚本 命令 shell 执行 nodejs 使用      更新时间:2023-09-26

我正试图找到一些好的库来使用nodejs执行shell脚本命令(例如:rm, cp, mkdir等)。最近没有关于可能的打包方案的明确文章。我读了很多关于执行同步的文章。但有些人说它已经过时了。真的,我迷路了,什么也找不到。我尝试安装execo -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'.

你有什么建议吗?

您可以简单地使用node的Child Process核心模块,或者至少使用它来构建您自己的模块。

子进程

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

特别是exec()方法。

child_process.exec ()

生成一个shell并在该shell中运行命令,完成后将标准输出和标准错误传递给回调函数。

下面是文档中的示例。

生成一个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}`);
});