Categories
JavaScript Answers

How to fix Node npm: command not found in bash?

To fix Node npm: command not found in bash, we install npm.

To do this, we run

apt-get install -y npm

to install npm with apt-get install.

Categories
JavaScript Answers

How to make simple API Calls with Node.js?

To make simple API calls with Node.js, we use the http module.

For instance, we write

const http = require("http");
const client = http.createClient(3000, "localhost");
const request = client.request("PUT", "/users/1");
request.write("stuff");
request.end();
request.on("response", (response) => {
  // ...
});

to call createClient to create a client object.

Then we call request to start a put request to the /users/1 URL.

Then we call write to write the request body.

And we call end to send the request.

We call on to listen for the 'response' event which is triggered when we receive a response.

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.