7

My problem is to figure out when to close a database connection from an expressjs backend to a sqlite database.

What I basically want to achieve is a database connection which is open during the whole server uptime and is closed on server shutdown.

var express = require('express')
var app = express()
var sqlite3 = require('sqlite3').verbose();

var db = new sqlite3.Database(data/Test.db);

//use db as needed 

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
});

//on shutdown db.close();

I had a look at these threats:

Stack overflow: process.on('exit', callback)

Github issue: App has no app.close()

But the suggested solutions wouldn't work for me if I kill me express server with ctrl+c.

So what would be a 'best practice' on how to handle an open database connection on server shutdown?

Community
  • 1
  • 1
Link1510
  • 101
  • 1
  • 8

1 Answers1

14

SIGINT is the signal you're looking for; most terminals send a SIGINT on Ctrl+C.

You could try something like this -

process.on('SIGINT', () => {
    db.close();
    server.close();
});
GPX
  • 3,506
  • 10
  • 52
  • 69
  • That worked for me. I was looking at 'SIGTERM', because I thought this would be send anyways. – Link1510 Mar 21 '17 at 13:16
  • @Link1510 I'd recommend going over the standard signals here - https://nodejs.org/docs/latest/api/process.html#event_exit_ – GPX Mar 21 '17 at 13:29