Categories
JavaScript Answers

How to fix ENOENT, no such file or directory with Node npm?

To fix ENOENT, no such file or directory with Node npm, we clear the npm cache.

To do this, we

  1. Run npm install
  2. Run npm cache clean to clear the npm cache
  3. Run npm install -g npm, then npm install
Categories
JavaScript Answers

How to get the redirected URL from the Node request module?

To get the redirected URL from the Node request module, we use the request property.

For instance, we write

const request = require("request");
const r = request.get("http://example.com", (err, res, body) => {
  console.log(res.request.uri.href);
});

to make a get request with request.get.

We get the redirect URL from the res.request.url.href property.

Categories
JavaScript Answers

How to solve “ReferenceError: expect is not defined” error message with Node?

To solve "ReferenceError: expect is not defined" error message with Node, we install chai.

To install it, we run

npm install chai

Then we write

const expect = chai.expect;

to get the chai.expect property.

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