簡體   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