sffc
sffc

Reputation: 6424

How to print output on Node.JS process exit event

Consider the following program.

var util = require("util");

process.on("exit", function(){
    util.puts("Hello World");
});

// Keep the program alive
setInterval(function(){}, 500);

The above program waits until it receives a signal to terminate. When the process exits, I expect "Hello World" to be printed to standard out. However, upon receiving a signal (I've tried SIGTERM, SIGINT, SIGHUP, and SIGKILL), the application fails to print the message. If I remove the setInterval line such that the process exits on its own, then the message is printed.

How can you make Node.JS print a message to the console (or to a file) when the process exits due to a signal?

Upvotes: 2

Views: 4023

Answers (2)

harryy000
harryy000

Reputation: 553

You could try the readLine module

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
//SIGINT gets triggered when a ctrl+c is done
rl.on('SIGINT', function() {
    console.log('shutting down');
});

Upvotes: 0

emars
emars

Reputation: 116

If you attach a listener for SIGINT (Interrupt signal), you can either perform an operation either in the process.exit listener or the SIGINT listener.

However, you can only perform synchronous operations in the process.exit block as it will only run once before exiting the program.

var util = require("util");

process.on("exit", function(){
    util.puts("Hello World");

    setTimeout(function(){
        //Won't run code in here
        util.puts("Something Async");
    },1);
});

process.on("SIGINT", function(){
    util.puts("You Pressed CTRL+C");
    somethingAsync(function(err){
        process.exit();
    });
});

// Keep the program alive
setInterval(function(){}, 500);

//OUTPUTS:
//You Pressed CTRL+C
//Hello World

Upvotes: 1

Related Questions