【问题标题】:Executing shell command using child_process in javascript在javascript中使用child_process执行shell命令
【发布时间】:2018-12-05 01:22:58
【问题描述】:

尝试从浏览器执行 shell 命令(任意)并使用 child_process 在 Ui 上打印结果。

无法从命令行异步获取结果。我在这里遗漏了什么吗?

   const exec = require('child_process').exec;
    app.post('/plan',(req, res) => {

      let cmd = exec('dir');
      let output = "";
      cmd.stdout.on('data', (data) => {
        //console.log(`stderr: ${data}`);
        output += data;
       });
      res.send(output);                          //not working
      console.log(output);                       //its empty
      cmd.stderr.on('data', (data) => {
          console.log(`stderr: ${data}`);
       });
      cmd.on('close', (code) => {
         console.log(`child process exited with code ${code}`);
      });

    });

【问题讨论】:

    标签: javascript node.js express asynchronous child-process


    【解决方案1】:

    shell 命令异步运行。您需要从回调函数中发送响应,以便它在完成执行时发送结果。

      cmd.stdout.on('data', (data) => {
        output += data;
        res.send(output); 
       });
    

    这样做可能会更干净:

    const exec = require('child_process').exec;
    app.post('/plan',(req, res) => {
      exec('dir', (error, stdout, stderr) => {
        if (error) {
          res.status(500).send(stderr);
          return;
        }
        res.send(stdout);
      });
    });
    

    【讨论】:

    • 如何访问 ui 上的标准输出?我收到的结果是body: (...) bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "basic" url: "http://localhost:3000/plan" __proto__: Response
    • 您需要将响应流读取为文本developer.mozilla.org/en-US/docs/Web/API/Response。试试fetch('http://localhost:3000/plan').then(response => response.text()).then(console.log)