Categories
JavaScript Answers

How to debug “EventEmitter memory leak detected. 11 listeners added” with Node?

To debug "EventEmitter memory leak detected. 11 listeners added" with Node, we can use the Node --trace=warnings option.

For instance, we run

node --trace-warnings

to trace the source of the warning when we run our app.

Categories
JavaScript Answers

How to shut down a Node Express server gracefully when its process is killed?

To shut down a Node Express server gracefully when its process is killed, we use the '@moebius/http-graceful-shutdown package.

For instance, we write

const express = require("express");
const GracefulShutdownManager =
  require("@moebius/http-graceful-shutdown").GracefulShutdownManager;

const app = express();

const server = app.listen(8080);

const shutdownManager = new GracefulShutdownManager(server);

process.on("SIGTERM", () => {
  shutdownManager.terminate(() => {
    console.log("Server is gracefully terminated");
  });
});

to create a GracefulShutdownManager object.

Then we call shutdownManager.terminate to shut down the Express app gracefully. when the SIGINT signal is received, which is when the Express process is killed.

Categories
JavaScript Answers

How to destroy or delete all records in the table with Node Sequelize?

To destroy or delete all records in the table with Node Sequelize, we call the destroy method.

For instance, we write

db.User.destroy({
  where: {},
  truncate: true,
});

to call destroy to destroy the table linked to the User model.

We set truncate to true to remove all the data in it.

Categories
JavaScript Answers

How to check if a collection exists in MongoDB native Node driver?

To check if a collection exists in MongoDB native Node driver, we call the listCollections method.

For instance we write

db.listCollections({ name: collName }).next((err, collinfo) => {
  if (collinfo) {
    // The collection exists
  }
});

to call listCollections with an object with the name property set to the collName collection name we’re looking for.

Then we call next with a callback that has the collection info set as the value of collinfo if it exists.

Categories
JavaScript Answers

How to fix Node.js cannot find module ‘mongodb’?

To fix Node.js cannot find module ‘mongodb’, we install the mongodb package.

To do this, we run

npm install mongodb 

to install the mongodb module in our project folder.