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.

Categories
JavaScript Answers

How to use the Underscore module with Node.js

To use the Underscore module with Node.js, we call require to include the underscore module.

For instance, we write

const _ = require("underscore");

to import the underscore module in our JavaScript code to use its functions.

Categories
JavaScript Answers

How to install Node.js nvm in Docker?

To install Node.js nvm in Docker, we run curl to install it.

For instance, in our dockerfile, we add

SHELL ["/bin/bash", "--login", "-c"]

RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
RUN nvm install 10.15.3

to run curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

to download the nvm install script and run bash to install it with the downloaded script.

And then we run

nvm install 10.15.3

to install nvm 10.15.3.