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?
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();
});