I'm quite new to node.js and I'm using it as a server to receive http.get requests from a browser, do some processing and return a result to the browser.
The processing is actually scraping a website using phantom.js/casper.js and because of the complications with using casper.js in node.js I'm executing it as a sub-process with the use of a shell script.
When I run the code below and make a request from the browser, the response seems to appear before the shell script has run. I tried using the async library to run the steps in series so that run.sh runs and returns a value before it's added to the response but it doesn't seem to work like that. Can anyone spot my stupid mistake?
Thanks in advance!
var express = require('express');
var app = express();
var sys = require('sys');
var exec = require('child_process').exec;
var async = require('async');
var auth = express.basicAuth('test', 'pass');
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
var result;
//app.use(auth);
app.get('/free/:u/:p', auth, function(req, res) {
async.series([
function(callback){
var puts = function (error, stdout, stderr) {
result = stdout;
}
exec("./run.sh " + req.params.u + " " + req.params.p, puts);
callback(null);
},
function(callback){
res.writeHead(200,{'Content-Type':'application/json'});
res.send(result)
callback(null);
}
]);
});
app.get('/', function(req, res) {
res.send('Hello!');
});