I'm trying to implement shell command execution I found here: node.js shell command execution
So I'm trying to get second answer (by Chris Eineke) working. But for now I get no output.
Here is my try:
run_cmd = (cmd, args, done) ->
spawn = require('child_process').spawn
child = spawn(cmd, args)
result = { stdout: '' };
child.stdout.on \data ! (buffer) ->
result.stdout += buffer
child.stdout.on \end !-> done()
result
dir = run_cmd(
'ls', ['-a']
, !-> console.log('done')
)
console.log dir.stdout
it compiles to:
run_cmd = function(cmd, args, done){
var spawn, child, result;
spawn = require('child_process').spawn;
child = spawn(cmd, args);
result = {
stdout: ''
};
child.stdout.on('data', function(buffer){
result.stdout += buffer;
});
child.stdout.on('end', function(){
done();
});
return result;
};
dir = run_cmd('ls', ['-a'], function(){
console.log('done');
});
console.log(dir.stdout);
But I can't see ls
results. Where is my mistake? Or what am I doing wrong?
You're not seeing results because run_cmd runs async and the result is empty when console.log dir.stdout
is ran. You should rather pass the results to your callback and do the logging there. Here's a working LiveScript version:
run_cmd = !(cmd, args, done) ->
spawn = require 'child_process' .spawn
child = spawn cmd, args
result = stdout: ''
child.stdout
..on \data !(buffer) ->
result.stdout += buffer
..on \end !->
done result
<-! run_cmd \ls <[ -a ]>
console
..log \done
..log it.stdout
Here we see multiple LS features used like paren-free chaining (spawn
line), braceless object definition (result
line), cascades (the ..on
and ..log
lines), backcalls (<-!
), word arrays (<[ array of words ]>
) and implicit argument (it
). For more info on them, refer to the LiveScript documentation.