4
var http = require("http");
var sys = require('sys')
var filename = process.ARGV[2];
var exec = require('child_process').exec;
var com = exec('uptime');


http.createServer(function(req,res){
  res.writeHead(200,{"Content-Type": "text/plain"});
  com.on("output", function (data) {
    res.write(data, encoding='utf8');
  });  
}).listen(8000);
sys.puts('Node server running')

How do I get the data streamed to the browser ?

1 Answer 1

13

If you're just generally asking whats going wrong, there are two main things:

  1. You're using child_process.exec() incorrectly
  2. You never called res.end()

What you're looking for is something more like this:

var http = require("http");
var exec = require('child_process').exec;

http.createServer(function(req, res) {
  exec('uptime', function(err, stdout, stderr) {
    if (err) {
      res.writeHead(500, {"Content-Type": "text/plain"});
      res.end(stderr);
    }
    else {
      res.writeHead(200,{"Content-Type": "text/plain"});
      res.end(stdout);
    }
  });
}).listen(8000);
console.log('Node server running');

Note that this doesn't actually require 'streaming' in the sense that the word is generally used. If you had a long running process, such that you didn't want to buffer stdout in memory until it completed (or if you were sending a file to the browser, etc), then you would want to 'stream' the output. You would use child_process.spawn to start the process, immediately write the HTTP headers, then whenever a 'data' event fired on stdout you would immediately write the data to HTTP stream. On an 'exit' event you would call end on the stream to terminate it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.