lundi 30 mars 2015

Node.js - wait for process.exit() to execute after earlier code is finished

In my node.js application I want to write some data to a logfile when the server is shutdown (thus when CTRL+C has been done in the cmd). The problem is that the process.exit() is called before the writing to the file is finished. I tried using a callback and jQuery $.Deferred.resolve(), but to no avail: probably because the file-write is async but I'd like to keep it asynchronous.

The callback code:



if (process.platform === "win32"){
var rl = readLine.createInterface ({
input: process.stdin,
output: process.stdout
});

rl.on ("SIGINT", function (){
process.emit ("SIGINT");
});

}

process.on ("SIGINT", function(){
var stopServer = function() {
//this happens way too early, the logger.log has not written it's data yet
process.exit();
};

var logServerStop = function(callback) {
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("");
callback();
};
logServerStop(stopServer);

});


And the logger.log code:



var fs = require('fs');
var filename = './output/logs/logfile.txt';

exports.log = function(data, addDate){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();

if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');

fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
});
}

});
};


I'd also like to keep the log-function as it is (so I wouldn't like having to add a callback-function parameter, I'd like my problem to be handled in the callback code. Thanks in advance.


Edit 1



process.on ("SIGINT", function(){
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("", false, function(){
process.exit();
});

});


And the logger.log changes:



exports.log = function(data, addDate, callback){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();

if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');

fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
});
}

});
if(typeof(callback)=='function'){ callback(); }
};

Aucun commentaire:

Enregistrer un commentaire