I'm trying to run an external command from node on a server and have the output of that command sent back to the client line by line. That is, I want to send the output as it is produced, not when the command has finished.
The server side code works fine -- the command is run and the output is read line by line. I'm passing a client callback to the server to call when new data arrives. This works for the first line of output, but not for any subsequent lines. I have verified that the server indeed receives subsequent lines of output, they just never arrive at the client.
The server code looks like this (simplified).
var spawn = require('child_process').spawn;
function run(cmd, cb) {
var child = spawn(cmd, []),
child.stdout.on('data', function(data) { cb(String(data)); });
}
socket.on("foo", function(cb) { return run("ls", cb); });
The client side uses this code (again simplified).
socket.emit("foo", function(data) {
console.log(data);
});
I do not get any error messages on the server or client side. Any insight into this would be appreciated.
Update
I solved this issue by using the socket explicitly to send data back to the client. For reference, the server code now looks like this.
function run(cmd, cb) {
var child = spawn(cmd, []),
child.stdout.on('data', function(data) {
socket.emit("output", String(data));
});
}
And the client.
socket.emit("foo", function(data) {
//
});
socket.on("output", function(data) {
console.log(data);
});