【问题标题】:Node-JS - Express and child_process capturing outputNode-JS - Express 和 child_process 捕获输出
【发布时间】:2022-02-12 07:48:51
【问题描述】:

我想知道是否有办法让快速服务器处理对 child_process 进程的请求。

例如,我希望能够向例如 cmd.exe 发送命令,并获得响应以发送给执行请求的客户端。

谢谢。

编辑:

到目前为止我的尝试是:

通过

生成child_process
var proc = spawn(config.cmd, config.args, { cwd: config.cwd });

然后通过管道输出:

proc.stdout.on('data', function(data) {res.send(data)});

但是,这实际上并没有返回数据,因为它返回了发送的命令。我想知道是否有类似的承诺功能:

proc.stdin.write("command").then

这是一个在命令之后没有结束的进程,它将继续运行。所以我不能等待所有的回复。

谢谢。

【问题讨论】:

    标签: node.js express child-process


    【解决方案1】:

    运行服务器:npm app.js

    // app.js
    const util = require('util');
    const exec = util.promisify(require('child_process').exec);
    const express = require('express');
    
    const PORT = 10080;
    
    const app = express();
    app.use(async (req, res) => {
       const cmd = 'echo "Hello from terminal"'; //replace this line with your code.
       const dir = await exec(cmd);
       res.json(`hello from server + ${dir.stdout}`);
    });
    
    app.listen(PORT, () => console.log(`Listining on port:${PORT}`));
    

    curl http://localhost:10080

    StatusCode        : 200
    StatusDescription : OK
    Content           : "hello from server + \"Hello from terminal\"\r\n"
    Headers           : {[Connection, keep-alive], [Keep-Alive, timeout=5],
                        [Content-Length, 48], [Content-Type, application/json;
    

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 2016-06-25
      • 2020-07-01
      • 2016-09-01
      相关资源
      最近更新 更多