Skip to content

Instantly share code, notes, and snippets.

@sfarthin
Created February 21, 2014 17:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfarthin/9139500 to your computer and use it in GitHub Desktop.
Save sfarthin/9139500 to your computer and use it in GitHub Desktop.
// See http://stackoverflow.com/questions/21934831/nodejs-express-stream-stdout-instantly-to-the-client
var cp = require("child_process"),
express = require("express"),
app = express();
app.get('/', function(req, res){
res.writeHead(200, { "Content-Type": "text/event-stream" });
var spw = cp.spawn('ping', ['127.0.0.1']),
str = "";
spw.stdout.on('data', function (data) {
str += data.toString();
console.log("data");
// Flush out line by line.
var lines = str.split("\n");
for(var i in lines) {
if(i == lines.length - 1) {
str = lines[i];
} else{
res.write(lines[i] + "\n");
}
}
});
spw.on('close', function (code) {
res.end(str);
});
spw.stderr.on('data', function (data) {
res.end('stderr: ' + data);
});
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment