Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a Node HTTP server who's response body is 'stdout' of a `echo hello world` spawn.
var spawn = require('child_process').spawn;
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
'Connection':'close',
'Transfer-Encoding':'identity' // 'chunked' can't be used unfortunately
// since the child_process won't know how
// to do the encoding on it's own stdout
});
// Hack, to force Node to flush the HTTP response headers
var flushed = response._send('');
var callback = function() {
spawn('echo', ['hello', 'world'], {
// Set the 'stdout' fd to the HTTP connection's fd.
customFds: [-1, request.connection.fd, -1]
});
// stream.destroy() is optional, and should be called if you DO NOT
// intend on sending additional data after the cp closes. IE the cp
// ending will close the stream (the cp's stdout).
request.connection.destroy();
};
// Wait until we're sure that the HTTP headers have been flushed
// (this might not be necessary...)
if (flushed) {
callback();
} else {
request.connection.on('flush', callback);
}
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment