Categories
JavaScript Answers

How to fix Node.js: SyntaxError: Cannot use import statement outside a module error?

To fix Node.js: SyntaxError: Cannot use import statement outside a module error, we use CommonJS modules.

For instance, we write

module.exports.func = () => {
  console.log("Hello World");
};

to define the func function and export it in mod.js.

Then we write

const myMod = require("./mod");
myMod.func();

to call require to require mod.js.

And we call myMod.func to call the function.

Categories
JavaScript Answers

How to call Node.js “require” function and parameters?

To call Node.js "require" function and parameters, we export a function.

For instance, we write

module.exports = (options) => {
  const app = options.app;
  const param2 = options.param2;
};

in lib.js to export a function.

Then we write

require("lib.js")({ app, param2 });

to require the lib.js file and call the function that’s imported.

Categories
JavaScript Answers

How to toggle between multiple .env files like .env.development with Node.js?

To toggle between multiple .env files like .env.development with Node.js, we use the dotenv library.

For instance, we write

require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` });

to call config with an object with the path property to point to the .env file path we want to use.

process.env.NODE_ENV is the NODE_ENV environment variable value.

Categories
JavaScript Answers

How to convert string to number with Node.js?

To convert string to number with Node.js, we call the parseInt function.

For instance, we write

const year = parseInt(req.params.year, 10);

to call parseInt to convert req.params.year to a decimal integer.

Categories
JavaScript Answers

How to update npm on Windows?

To update npm on Windows, we run npm install.

We run

npm install npm@latest

to update npm to the latest version.