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

3

我正在尝试执行一个exe文件。通过命令行执行时,它可以正常工作并打印我想要的数据。但是使用node.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");

2
err 里面有没有任何东西? - hexacyanide
没有输出任何内容。 - Sush
我认为即使它没有打印错误,故障也可能在exe spawn进程后面,有其他方法可以使用node.js执行exe文件吗? - Sush
如果第二个 console.log() 是未定义的,那么第一个呢? - hexacyanide
以下是关于编程的内容,请将其从英语翻译成中文。只返回已翻译的文本:两个 console.log(err) console.log(data.toString()); 都没有输出任何内容。 - Sush
2个回答

2
只需像下面这样运行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


@Sush 我错了。我读错了代码。发生的情况是请求已经完成,而end事件处理程序在exec调用完成之前运行。你需要在req.on('end')处理程序中运行exec - Bulkan
那么我应该在req.on("data", function (value) {})内写什么? - Sush
不需要使用 req.on("data", function (value) {}); 对吗? - Sush
抱歉,它没有打印任何东西 :-( - Sush

2

试试这样做。

我认为这会有所帮助。

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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接