Sush
Sush

Reputation: 1457

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

Here am trying to execute an exe file. while executing through command line it is working properly and print the data I want. But using node.js it print the data as undefined. and here is the code am using

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

Upvotes: 3

Views: 488

Answers (2)

divz
divz

Reputation: 7957

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

Upvotes: 2

Bulkan
Bulkan

Reputation: 2596

Just run the exec call like the following.

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

Listening to the data event on req switches it into a streaming/flowing mode

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

Upvotes: 2

Related Questions