Nodejs - output stream to browser

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 to get data transferred to the browser?

+4
source share
1 answer

If you just usually ask what is going wrong, there are two main things:

  • You are using child_process.exec() incorrectly
  • You never called res.end()

What you are looking for is something more:

 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 does not actually require β€œstreaming” in the sense that the word is commonly used. If you had a lengthy process, so you did not want to buffer stdout in memory until it exits (or if you send the file to the browser, etc.), then you will want to "flush" the output. You should use child_process.spawn to start the process, immediately write the HTTP headers, then whenever the "data" event is fired on stdout, you immediately write the data to the HTTP stream. In the 'exit' event, you call the end in the stream to terminate it.

+11
source

All Articles