Reputation: 58
I’m trying to run child process in next code:
run = function (cmd, callback) {
var spawn = require('child_process').spawn;
var command = spawn(cmd);
var result = '';
command.stdout.on('data', function (data) {
result += data.toString();
});
command.on('exit', function () {
callback(result);
});
}
execQuery = function (cmd) {
var result = {
errnum: 0,
error: 'No errors.',
body: ''
};
run(cmd, function (message) {
result.body = message;
console.log(message);
});
return result;
}
After execution execQuery('ls') result.body is always empty, but console.log is contain value.
Upvotes: 1
Views: 2995
Reputation: 146164
I ran a quick test and the command's exit
event is firing before all of stdout
s data is drained. I at least got the output captured and printed if I changed your exit
handler to look for command.stdout
's end
event.
command.stdout.on('end', function () {
callback(result);
});
That should help a bit. Note there are existing libraries you might want to use for this and a truly correct implementation would be significantly more involved than what you have, but my change should address your current roadblock problem.
Random tip: it is the node convention to always reserve the first argument of callback functions for an error and your snippet is inconsistent with that convention. You probably should adjust to match the convention.
Oh sorry, let me address your question about result.body
. The run
function is ASYNCHRONOUS! That means that your return result;
line of code executes BEFORE the run
callback body where result.body = message;
is. You can't use return values like that anywhere in node when you have I/O involved. You have to use a callback.
Upvotes: 1