使用nodejs在不同会话中执行终端命令

Executing terminal command in different sessions with nodejs

我想用 nodejs 脚本执行 shell 命令。我有一个问题

As nodejs documentation says;

const { spawn } = require('child_process');

const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

效果很好。

但是如果我想要 运行 一个无穷无尽的命令并且我想要 运行 另一个命令怎么办。

例如;

const { spawn } = require('child_process');

    const simpleServer = spawn('python', ['-m', 'SimpleHTTPServer', '1234']);

    simpleServer.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });

    simpleServer.stderr.on('data', (data) => {
      console.log(`stderr: ${data}`);
    });

    simpleServer.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
    });

    gulper.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });

    gulper.stderr.on('data', (data) => {
      console.log(`stderr: ${data}`);
    });

    gulper.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
    });

有什么方法可以在不同的会话中做到这一点吗?

你不能运行他们分开。您必须在 NodeJS 中使用 Promise 或异步工具。