Categories
JavaScript Answers

How to install the babel-polyfill library with JavaScript?

To install the babel-polyfill library with JavaScript, we run npm install.

For instance, we run

npm install --save-dev  @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill

to install the @babel/polyfill package along with the other required Babel packages.

Categories
JavaScript Answers

How to properly export an ES6 class in Node.js?

To properly export an ES6 class in Node.js, we set the class as the value of module.exports.

For instance, in person.js, we write

"use strict";

module.exports = class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  display() {
    console.log(this.firstName, this.lastName);
  }
};

to export the Person class.

Then we write

const Person = require("./person.js");

const someone = new Person("First name", "Last name");
someone.display();

to require the person.js module and then create a Person instance.

Categories
JavaScript Answers

How to use HTML as the view engine in Node.js Express?

To use HTML as the view engine in Node.js Express, we use the express.static middleware.

For instance, we write

app.use(express.static(__dirname + "/public"));

to make the /public folder in the project folder a static file directory.

Then we can put HTML files in there and open them directly.

Categories
JavaScript Answers

How to load and execute external JavaScript file in Node.js with access to local variables?

To load and execute external JavaScript file in Node.js with access to local variables, we create a module with the variables and require the module.

For instance, we write

const PI = 3.14;

exports.area = (r) => {
  return PI * r * r;
};

exports.circumference = (r) => {
  return 2 * PI * r;
};

in circle.js to export the area and circumference functions.

Then we write

const circle = require("./circle");
console.log(circle.area(4));

to require the circle.js file and call the area function from circle.js.

Categories
JavaScript Answers

How to change value of process.env.PORT in Node.js?

To change value of process.env.PORT in Node.js, we set the PORT variable.

For instance, we run ‘

$ PORT=1234 node app.js

from Unix or Linux to set the PORT environment variable to 1234 before running app.js.

We can do the same thing with

$ export PORT=1234
$ node app.js

On Windows, we run

set PORT=1234

to set the port.

And on Windows PowerShell, we run

$env:PORT = 1234

to do the same thing.