I am writing a Node/Express web application as part of my university module. At the moment, the application is very simple and I have three files: db.js, app.js, and entry.js.
The db.js module creates Sequelize instance and exports it so it’s available to other modules. This is the entire code within db.js:
const { Sequelize } = require('sequelize');
const dbConfig = require('./dbconfig');
// Create Sequelize instance
const NODE_ENV = process.env.NODE_ENV.trim();
const sequelize = new Sequelize(dbConfig[NODE_ENV]);
module.exports = sequelize;
The app.js imports the express module, creates an express application and exports it:
const express = require("express");
const app = express();
module.exports = app;
The entry.js is run by npm run devstart
from the terminal (cmd, Windows). It runs SET NODE_ENV=dev && nodemon ./app/bin/entry.js
script within package.json.
I want to gracefully handle the closure of server and sequelize instances, so my entry.js looks like this:
const sequelize = require('../../db/db');
const app = require('../app');
const port = 3000;
// Test database connection
const testDatabaseConnection = async () => {
try {
await sequelize.authenticate();
console.log('Database connection successfull.');
} catch (error) {
console.error('Unable to connect to the database:', error);
throw(error);
}
}
// Attempt to start the server
const serverStart = async () => {
try {
await testDatabaseConnection();
const server = app.listen( port, () => {
console.log(`Server listening on port ${port}.`);
});
return server;
} catch(error) {
console.error('Failed to start server:', error);
process.exit(1);
}
}
serverStart().then( (server) => {
// Listen for process termination signals
process.on('SIGINT', () => gracefulShutdown(server));
process.on('SIGTERM', () => gracefulShutdown(server));
} );
// Gracefully close the application
const gracefulShutdown = async (server) => {
console.log('Server is shutting down.');
try {
await new Promise( (resolve, reject) => {
server.close( (error) => (error ? reject(error) : resolve()) );
} );
await sequelize.close();
console.log('Database connection closed successfully.');
process.exit(0);
} catch(error) {
console.error('Error during shutdown:', error);
process.exit(1);
}
};
When I start and terminate the nodemon process with Ctrl + c in the terminal (cmd, Windows), I sometimes get this output:
Executing (default): SELECT 1+1 AS result
Database connection successful.
Server listening on port 3000.
Server is shutting down.
^C^CTerminate batch job (Y/N)?
But, I am expecting it to be this:
Executing (default): SELECT 1+1 AS result
Database connection successful.
Server listening on port 3000.
Server is shutting down.
Database connection closed successfully.
^C^CTerminate batch job (Y/N)?
I am not sure why this happens. When I replace the nodemon
with node
in package.json script, the output seems to be consistent and I don’t get this issue.
I apologise if the question is too long.
Any input or feedback is greatly appreciated.
Many thanks.
koolaidkid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.