在 Node.js 中生成一个子进程,数据未定义

spawn a child process in node.js, data is undefined

本文关键字:一个 子进程 未定义 数据 js Node      更新时间:2023-09-26

这里我试图执行一个exe file. 通过命令行执行时,它工作正常并打印我想要的数据。但是使用节点.js它将数据打印为undefined .这是我使用的代码

var server = http.createServer(function (req, res) {   
switch (req.url) {    
case '/start':
    console.log("begin...............");        
        req.on("data", function (value) {             
            exec('CALL hello.exe', function(err, data) {                
                 console.log(err)
                console.log(data.toString());                       
           });              
        });
        req.on("end", function () { 
            console.log(data);      // prints undefined 
            console.log(JSON.stringify(data));
            console.log("hello");
            console.log("before--------------");               
            res.writeHead(200);
            res.end(data);
        });        
    break;
}
});
server.listen(8080);
console.log("Server running on the port 8080");

试试这样。

我认为这会对你有所帮助。

var http = require('http');
var exec = require('child_process').execFile;
var server = http.createServer(function (req, res) {
switch (req.url) {
  case '/start':
      console.log("begin...............");

        exec('hello.exe', function(err, data) {
          console.log(err);
          console.log(data);
          console.log(data);      // prints undefined 
          console.log(JSON.stringify(data));
          console.log("hello");
          console.log("before--------------");
          res.writeHead(200);
          res.end(data);
        });
      break;
  }
});
server.listen(8080);
console.log("Server running on the port 8080")

只需像下面这样运行exec调用。

var http = require('http');
var exec = require('child_process').exec;
var server = http.createServer(function (req, res) {
switch (req.url) {
  case '/start':
      console.log("begin...............");

        exec('CALL hello.exe', function(err, data) {
          console.log(err);
          console.log(data);
          console.log(data);      // prints undefined 
          console.log(JSON.stringify(data));
          console.log("hello");
          console.log("before--------------");
          res.writeHead(200);
          res.end(data);
        });
      break;
  }
});
server.listen(8080);
console.log("Server running on the port 8080");

req上侦听 data 事件会将其切换到流式传输/流模式

http://nodejs.org/api/stream.html#stream_event_data