3

这里我试图执行一个exe file. 通过命令行执行时,它工作正常并打印我想要的数据。但是使用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");
4

2 回答 2

2

Try like this.

I think this will helps you.

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")
于 2013-11-07T03:43:14.660 回答
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");

监听data事件req将其切换到流/流动模式

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

于 2013-11-04T04:32:58.987 回答