Calling Express Route internally from inside NodeJS

The ‘usual’ or ‘correct’ way to handle this would be to have the function you want to call broken out by itself, detached from any route definitions. Perhaps in its own module, but not necessarily. Then just call it wherever you need it. Like so: function updateSomething(thing) { return myDb.save(thing); } // elsewhere: router.put(‘/api/update/something/:withParam’, function(req, … Read more

Node.js – wait for multiple async calls

I’m a big fan of underscore/lodash, so I usually use _.after, which creates a function that only executes after being called a certain number of times. var finished = _.after(2, doRender); asyncMethod1(data, function(err){ //… finished(); }); asyncMethod2(data, function(err){ //… finished(); }) function doRender(){ res.render(); // etc } Since javascript hoists the definition of functions defined … Read more

Run shell script with node.js (childProcess)

The exec function callback has error, stdout and stderr arguments passed to it. See if they can help you diagnose the problem by spitting them out to the console: exec(‘~/./play.sh /media/external/’ + req.params.movie, function (error, stdout, stderr) { console.log(‘stdout: ‘ + stdout); console.log(‘stderr: ‘ + stderr); if (error !== null) { console.log(‘exec error: ‘ + … Read more

Whats the smartest / cleanest way to iterate async over arrays (or objs)?

Checkout the async library, it’s made for control flow (async stuff) and it has a lot of methods for array stuff: each, filter, map. Check the documentation on github. Here’s what you probably need: each(arr, iterator, callback) Applies an iterator function to each item in an array, in parallel. The iterator is called with an … Read more