Categories
JavaScript Answers

How to get Mongoose connect error with Node?

To get Mongoose connect error with Node, we call connect with a callback as the 2nd argument.

For instance, we write

mongoose.connect("mongodb://localhost/dbname", (err) => {
  if (err) {
    throw err;
  }
});

to call connect with a callback as the 2nd argument.

We get connection errors from err if there’s any.

Categories
JavaScript Answers

How to fix libsass bindings not found when using node-sass in Node?

To fix libsass bindings not found when using node-sass in Node, we upgrade to gulp-sass 2.

To do this, we run

npm uninstall --save-dev gulp-sass
npm install --save-dev gulp-sass@2

to uninstall the original version of gulp-sass with npm uninstall.

Then we install gulp-sass 2 with npm install.

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.