Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js process on exit not work using forever

Tags:

node.js

I want some work on process exiting.

But process.on('exit') is not working using express or socket.io or mysql, etc.

process.on('exit', function() {
    console.log('Server exit.');
});

only this code is working.

var mysql = require('mysql');
var conn = mysql.createConnection();

conn.connect();

process.on('exit', function() {
    console.log('Server exit.');
});

this is not working.

like image 940
Lansi Avatar asked Sep 21 '13 04:09

Lansi


2 Answers

You can make it work by doing two simple things:

  1. Instead of using the exit event, use the SIGINT event (instead of process.on('exit',function(){/*stuff here*/}); use process.on('SIGINT',function(){/*stuff here*/});
  2. When starting the forever script, instead of just doing forever start your-script.js, type forever start your-script.js --killSignal=SIGINT

this works for me, but my script doesn't use much mysql and doesn't use any express, so it might not work for you

like image 181
markasoftware Avatar answered Sep 23 '22 15:09

markasoftware


That's because once you initialize express(), say (specifically: start the server), or create a MySQL connection, or do anything else that "lives in the background", node will not exit, so will not called you .on('exit').

It will not exit because it has pending tasks. It's just like if you were to invoke setInterval().

If you disconnect the MySQL connection, or stop the express server, it will then exit and invoke you handler.

like image 29
Nitzan Shaked Avatar answered Sep 23 '22 15:09

Nitzan Shaked