Title: Node.js - wait for process.exit() to execute after earlier code is finished
Tags: javascript;node.js;asynchronous;callback;fs
Question: 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(); }
};
```

Comment: Why avoid a callback function to your `log` method? It's the simplest solution. It doesn't mean you have to use it every time.

Comment: Can you show that attempt, please? Where exactly did you add the `fn()` call, and how did you modify your sigint handler?

Comment: You'll need to put it in the asynchronous `open`/`write` callbacks of course, otherwise it's equivalent to what you've done before!

Comment: I tried adding a callback parameter to the `log` method, but for some reason the callback would never be called. The logger wrote the data to the logfile as intended, but `process.exit()` never happened. I tried adding the line "if(typeof(fn)=='function'){ fn(); }" to the end of my `log` method, which fixed the issue of the `process.exit()` not happening but the file-write did not happen again.

Comment: I edited my post with the changes you requested to see.

Comment: Thank you! I didn't think it through that much, the `write` and `open` functions are indeed async so I should have put that line there. I was thinking that I just want to callback as soon as the `log` function finished but as the other 2 are async, the log function finished before the others in it had finished.


Here is another answer: Please see the edits to the log function.

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

        });
     };
```

In callback you can pass your error as first parameter, then when you call logger.log you can do this as below:

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

Comment for this answer: Please follow the edits. if you are editing your log function you can call your callback after you write your log file.
Comment for this answer: I'm afraid your suggestion didn't fix it
Comment for this answer: Thank you for your effort, but the above response already helped me out with the same idea! :) (also - in your suggestion I wouldn't really want the `err` as parameter for my callback). Thanks though!

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 6, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:03/30/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><node.js><asynchronous><callback><fs>', 'Title': 'Node.js - wait for process.exit() to execute after earlier code is finished', 'ViewCount': 2191, 'id': 29341993, 'user_AboutMe': '', 'user_AccountId': 1517202.0, 'user_DisplayName': 'Fluppe', 'user_Reputation': 450.0, 'user_Views': 72.0, 'user_id': 1417942.0}}