Categories
JavaScript Answers

How to fix ‘Error: require() of ES modules is not supported’ when importing node-fetch?

To fix ‘Error: require() of ES modules is not supported when importing node-fetch’, we call the import function.

For instance, we write

import { RequestInfo, RequestInit } from "node-fetch";

const fetch = async (url: RequestInfo, init?: RequestInit) => {
  const { default: fetch } = await import("node-fetch");
  return fetch(url, init);
};

to define the fetch function that calls import to import node-fetch.

And then we get the fetch function from the returned promise with await and destructuring.

Finally, we return the promise returned by calling fetch with the url and init object.

Categories
JavaScript Answers

How to print formatted console output with Node.js?

To print formatted console output with Node.js, we use the sprintf-js module.

For instance, we write

const { sprintf } = require("sprintf-js");

console.log(sprintf("Space Padded => %10.2f", 123.4567));

to call sprintf with the format string and the value we want to print.

We round the number to 2 decimal places with %10.2f and return the formatted string which we print with console.log.

Categories
JavaScript Answers

How to connect to MongoDB and authenticate with Node.js?

To connect to MongoDB and authenticate with Node.js, we call the authenticate method.

For instance, we write

Db.authenticate(user, password, (err, res) => {
  // callback
});

to call authenticate with the user username and password to connect to the database with the credentials.

We get the result from the callback.

Categories
JavaScript Answers

How to fix the ‘Not compatible with your operating system or architecture: fsevents@1.0.11’ error on Node on Mac?

To fix the ‘Not compatible with your operating system or architecture: fsevents@1.0.11’ error on Node on Mac, we skip installing optional dependencies.

To do this, we run

npm install --no-optional

to run npm install with the --no-optional flag to skip installing optional dependencies.

Categories
JavaScript Answers

How to get a variable from a file to another file in Node.js?

To get a variable from a file to another file in Node.js, we use modules.

For instance, we write

module.exports = { clientIDUnsplash: "SuperSecretKey" };

to export an object with the clientIDUnsplash property in unsplash.js.

Then we write

const { clientIDUnsplash } = require("./unsplash");

to call require to require the unsplash.js file and get the clientIDUnsplash property from the returned object.