Categories
JavaScript Answers

How to run Node.js app with ES6 features enabled?

To run Node.js app with ES6 features enabled, we set the presets option.

For instance, in package.json, we write

{
  "dependencies": {
    "babel-cli": "^6.0.0",
    "babel-preset-es2015": "^6.0.0"
  },
  "scripts": {
    "start": "babel-node --presets es2015 app.js"
  }
}

to add the babel-preset-es2015 package.

And we set the --presets option when we run babel-node to enable the ES6 features.

Categories
JavaScript Answers

How to read and write a text file in TypeScript and Node.js?

To read and write a text file in TypeScript and Node.js, we call the readFileSync function.

For instance, we write

import { readFileSync } from "fs";

const file = readFileSync("./filename.txt", "utf-8");

to call readFileSync to read filename.txt into a Unicode string.

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.