Created
February 21, 2014 17:56
-
-
Save sfarthin/9139500 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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