Archive

run shell from nodejs function

I have not inveted this one, but thought I share it. Here is how you can run shell commands from your node.js program:

var runShell = function(command){

	var sys = require('sys'),
			exec = require('child_process').exec;
	
	function puts(error, stdout, stderr) { 
		sys.puts(stdout); 
	}
	
	exec(command, puts);
}

// Example.
runShell('ls');

If you want to package this code into a module, it would look something like this:

// Usage:
// var sh = require('./shell');
// sh.run('ls');

exports.run = function(command){
	var sys = require('sys'),
			exec = require('child_process').exec;
	
	function puts(error, stdout, stderr) { 
		sys.puts(stdout); 
	}
	
	exec(command, puts);
}

Comments: