Node.js - 等待process.exit()在早期代码完成后执行

时间:2015-03-30 08:53:59

标签: javascript node.js asynchronous callback fs

在我的node.js应用程序中,我想在服务器关闭时将一些数据写入日志文件(因此在cmd中完成了CTRL + C)。问题是在写入文件完成之前调用process.exit()。我尝试使用callback和jQuery $.Deferred.resolve(),但无济于事:可能是因为文件写入是异步的,但我希望保持异步。
回调代码:

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);  

});

logger.log代码:

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.");
                }
            });
        }

    });
};

我还希望保持日志功能不变(因此我不想添加回调函数参数,我希望我的问题能够在回调代码。提前致谢。

编辑1

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

});

logger.log更改:

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(); }
};

1 个答案:

答案 0 :(得分:0)

请参阅日志功能的编辑。

    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);
                //execute call back here.
                if(typeof callback === 'function'){ 
                  callback(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.");
                    }
                    //execute call back here.
                    if(typeof callback === 'function'){ 
                      callback(err); 
                    }
                });
            }

        });
     };

在回调中,您可以将错误作为第一个参数传递,然后当您调用logger.log时,可以执行以下操作:

process.on ("SIGINT", function(){
    logger.log("SERVER SHUTDOWN: ", true);
    logger.log("-----------------------------------------");
    logger.log("", false, function(e){
        if(e){
          //Handle error here.
        }
        process.exit();
    });
});