Categories
JavaScript Answers

How to handle errors thrown by require() module in Node.js?

To handle errors thrown by require() module in Node.js, we use a try-catch block.

For instance, we write

let m;
try {
  m = require(modulePath);
} catch (e) {
  if (e.code !== "MODULE_NOT_FOUND") {
    throw e;
  }
  m = backupModule;
}

to wrap the require call in a try block.

And then we add a catch block that checks the error code.

If it’s not 'MODULE_NOT_FOUND', then we throw the e error.

Otherwise, we set m to backupModule.

Categories
JavaScript Answers

How to fix Error: getaddrinfo ENOTFOUND in Node.js for get call?

To fix Error: getaddrinfo ENOTFOUND in Node.js for get call, we should make sure the URL is pointing to a valid location.

For instance, we write

const optionsGet = {
  host: "localhost",
  port: 3010,
  path: "/quote/random",
  method: "GET",
};

const reqGet = https.request(optionsGet, (res) => {});

to call https.request with the valid host and path to make a get request to https://localhost:3010/quote/random

Categories
JavaScript Answers

How to modify the Node.js request default timeout time?

To modify the Node.js request default timeout time, we set the timeout property.

For instance, we write

const http = require("http");
const server = http
  .createServer((req, res) => {
    setTimeout(() => {
      res.writeHead(200, { "Content-Type": "text/plain" });
      res.end("Hello World\n");
    }, 200);
  })
  .listen(1337, "127.0.0.1");

server.timeout = 20;
console.log("Server running at http://127.0.0.1:1337/");

to create a web server with createServer.

And we set the request timeout by setting the server.timeout property to a time milliseconds.

Categories
JavaScript Answers

How to store DB config in a Node.js and Express app?

To store DB config in a Node.js and Express app, we store it in an .env file.

For instance, we write

DATABASE_PASSWORD=pw
DATABASE_NAME=some_db

in our .env file.

Then we write

require("dotenv").config();
const password = process.env.DATABASE_PASSWORD;

to load the .env file with the dotenv package.

And then we get the DATABASE_PASSWORD environment variable value with process.env.DATABASE_PASSWORD.

Categories
JavaScript Answers

How to fix ‘gulp’ is not recognized as an internal or external command with JavaScript?

To fix ‘gulp’ is not recognized as an internal or external command with JavaScript, we install the gulp package.

To install it, we run

npm install -g gulp

to install gulp globally.