使用子进程执行 shell 命令

Executing shell command using child process

我正在尝试执行命令以使用 ganache 分叉一条链。我一直在努力寻找一种以编程方式执行 fork 的方法,所以我想尝试通过子进程执行它。

我使用的代码是:

const { exec } = require("child_process");
const ganache = require("ganache");

const ls = exec('ganache-cli --fork https://speedy-nodes-nyc.moralis.io/KEY_HERE/bsc/mainnet/archive', function (error, stdout, stderr) {
  if (error) {
    console.log(error.stack);
    console.log('Error code: ' + error.code);
    console.log('Signal received: ' + error.signal);
  }
  console.log('Child Process STDOUT: ' + stdout);
  console.log('Child Process STDERR: ' + stderr);
});

ls.on('exit', function (code) {
  console.log('Child process exited with exit code ' + code);
});

但是当我运行这个的时候,根本就没有输出。没有错误或它只是对程序进行的任何操作,就好像此代码不存在一样。当我用 'dir' 替换命令时,它可以完美运行并列出目录中的文件。即使我删除节点地址并仅使用“ganache-cli --fork”作为命令,也没有任何反应。

为什么添加 ganache 命令后没有任何反应?

如果您查看 child process 文档,他们会说 exec:

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

但是,Ganache 是一个持续 运行 的进程,在您终止它之前不会“完成”。这允许您向 Ganache 发送多个请求而不会关闭它。