Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Writing a function to return spawn stdout as a string

Tags:

node.js

I'm trying to return the output of this function as a string, but it keeps returning as undefined. Where am I going wrong?

function run(cmd){     var spawn = require('child_process').spawn;     var command = spawn(cmd);     var result = '';     command.stdout.on('data', function(data) {             result += data.toString();     });     command.on('close', function(code) {             return result;     }); } console.log(run('ls')); 
like image 497
Billions McMillions Avatar asked Mar 20 '13 04:03

Billions McMillions


2 Answers

Your function returns immediately after command.on statement. The return statement in your callback for the close event is returned to nowhere. The return belongs to event callback, not to run().

Put console.log call instead of return result.

Generally speaking you should write something like:

function run(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('close', function(code) {         return callback(result);     }); }  run("ls", function(result) { console.log(result) }); 
like image 172
fuwaneko Avatar answered Sep 22 '22 03:09

fuwaneko


var spawn = require('child_process').spawn,     command  = spawn('ls', ['/tmp/']); command.stdout.pipe(process.stdout); 

The following link is exactly the same question as yours.

like image 37
Marcel Avatar answered Sep 20 '22 03:09

Marcel