繁体   English   中英

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

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

这里我试图执行一个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");

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

试试这样吧。

我想这会对你有所帮助。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM