When I'm debugging I start and terminate my node process a bunch of times. That makes this happen:
2014-07-20T15:53:19.162-0400 [conn352] authenticate db
2014-07-20T15:53:19.163-0400 [conn353] authenticate db
2014-07-20T16:13:59.631-0400 [conn354] authenticate db
2014-07-20T16:13:59.635-0400 [conn355] authenticate db
2014-07-20T16:13:59.636-0400 [conn356] authenticate db
2014-07-20T16:13:59.636-0400 [conn357] authenticate db
2014-07-20T16:19:01.747-0400 [conn358] authenticate db
2014-07-20T16:19:01.750-0400 [conn359] authenticate db
2014-07-20T16:19:01.751-0400 [conn360] authenticate db
2014-07-20T16:19:01.767-0400 [conn361] authenticate db
2014-07-20T16:19:33.227-0400 [conn362] authenticate db
2014-07-20T16:19:33.229-0400 [conn363] authenticate db
2014-07-20T16:19:33.230-0400 [conn364] authenticate db
2014-07-20T16:19:33.239-0400 [conn365] authenticate db
2014-07-20T17:04:08.577-0400 [conn366] authenticate db
2014-07-20T17:04:08.579-0400 [conn367] authenticate db
2014-07-20T17:04:08.580-0400 [conn368] authenticate db
2014-07-20T17:04:08.580-0400 [conn369] authenticate db
2014-07-20T17:05:15.783-0400 [conn370] authenticate db
2014-07-20T17:05:15.785-0400 [conn371] authenticate db
How can I close the mongodb connection (db.close()
) before terminating the node process? Is there some way to add an event listener like beforeunload
in client-side JS? Or do I have to configure a db option to automatically do that?
You can listen for the 'exit' event on process
, but you can't execute anything asynchronous in there because nothing inside your 'exit' handler can/will keep the process open.
What you should do instead of forcefully exiting your process is to let it exit naturally by closing any open connections, servers, etc.