EDIT: This seems impossible to do because the createWriteStream() and other error emitters doesn't necessarily emit errors at the next tick, so this wait cannot be done. Actually, if I shutdown() that means that I want to finish the process immediately, so it's ok if I don't get any error.
var fs = require ("fs");
var s;
var init = function (cb){
cb ();
};
var shutdown = function (cb){
cb (wait);
};
var wait = function (){
//Some kind of wait
process.exit ();
};
init (function (){
s = fs.createWriteStream ("?invalid").on ("error", console.error); //This emits an error
});
shutdown (function (cb){
s.on ("close", function (error){
if (error) console.error (error);
cb ();
});
s.end ();
cb ();
});
If you execute this code you won't get any error because the process is finished before the error is printed. If you change the wait() function to this,
var wait = function (){
//Some kind of wait
setTimeout (function (){
process.exit ();
}, 1000);
};
the error is printed and after 1s the process finishes. I want to wait to the error callback and then exit without setting a timer. I've tried with nextTick() but doesn't work.
Here's a simplified version of what you're trying to achieve:
var fs = require ("fs");
var s;
var init = function (cb){
cb ();
};
var shutdown = function(error){
console.log(error);
process.exit();
};
init(function (){
s = fs.createWriteStream("?invalid");
s.on("error", shutdown);
s.on ("close", shutdown);
});