Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to close Database with node-sqlite3 and express?

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?

like image 935
Link1510 Avatar asked Mar 21 '17 13:03

Link1510


People also ask

Do you need to close SQLite connection?

The sqlite3 module connect() ; the connection must be closed at the end of the session with the . close() command. While the connection is open, any interactions with the database require you to make a cursor object with the . cursor() command.

How do I close a SQLite database?

close( conn ) closes the SQLite connection by using the MATLAB® interface to SQLite. The SQLite connection object remains open until you close it using the close function. Always close this object when you finish using it.

Can I use SQLite with node js?

The sqlite3 module also works with node-webkit if node-webkit contains a supported version of Node. js engine. (See below.) SQLite's SQLCipher extension is also supported.

What is the use of the sqlite3 library?

SQLite is a C library that provides a lightweight disk-based database that doesn't require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage.


1 Answers

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();
});
like image 158
GPX Avatar answered Sep 22 '22 03:09

GPX