Reputation: 65
I'm having trouble wrapping my head around the asynchronous nature of node.js. Lets suppose I wanted a route that executed an 'ls' command and returned the results (as a string) to browser. How would would one go about this using child_process.exec? Below is incorrect, but along the lines of what I'm struggling with:
function dir_list() {
var sys = require('sys');
var exec = require('child_process').exec
child = exec('ls -la', function(error, stdout, stderr) {
//I would like to return stdout but can't figure out how
return stdout;
});
return child;
}
app.get('/', function(req, res){
res.render('index', {
title: 'MyPage',
subtitle: 'Below is a directory listing',
results: dir_list()
});
This isn't the entire code of my app.js but essentially i'm looking for help on getting dir_list() to set the results variable as the output of "ls -la".
Upvotes: 1
Views: 5294
Reputation: 25466
pass callback to your dir_list and call it with ls -la result
function dir_list(cb) {
var sys = require('sys');
var exec = require('child_process').exec
child = exec('ls -la', function(error, stdout, stderr) {
//I would like to return stdout but can't figure out how
cb(stdout);
});
}
app.get('/', function(req, res){
dir_list(function(dir_list_output) {
res.render('index', {
title: 'MyPage',
subtitle: 'Below is a directory listing',
results: dir_list_output});
});
});
Upvotes: 11