Categories
JavaScript Answers

How to host multiple Node.js sites on the same IP/server with different domains?

To host multiple Node.js sites on the same IP/server with different domains, we call the listen method with the domain.

For instance, we write

const server = require("diet");

const app = server();
app.listen("http://example.com/");
app.get("/", ($) => {
  $.end("hello world ");
});

const sub = server();
sub.listen("http://subdomain.example.com/");
sub.get("/", ($) => {
  $.end("hello world at sub domain!");
});

const other = server();
other.listen("http://other.com/");
other.get("/", ($) => {
  $.end("hello world at other domain");
});

to create the server with the diet package.

Then we call listen with the domain or subdomain URL to list to request to.

We call get with each server to listen for get request from /.

Categories
JavaScript Answers

How to fix Node Version Manager (NVM) not recognized on Windows?

To fix Node Version Manager (NVM) not recognized on Windows?, we’ve to install it.

To install it, we download nvm from https://github.com/coreybutler/nvm-windows/releases.

Then we pick nvm-setupp.zip from the page.

We then unzip the file and click on the installer.

Finally, we run nvm to check if it’s installed.

Then we run nvm install 10 to install Node 10.

We run node -v to check the node version.

We check the installed versions with nvm list.

And we use nvm use 10 to use Node version 10.

Categories
JavaScript Answers

How to read file from aws s3 bucket using Node fs?

To read file from aws s3 bucket using Node fs, we create a write stream.

For instance, we write

const s3 = new AWS.S3({ apiVersion: "2006-03-01" });
const params = { Bucket: "myBucket", Key: "myImageFile.jpg" };
const file = require("fs").createWriteStream("/path/to/file.jpg");
s3.getObject(params).createReadStream().pipe(file);

to call createWriteStreamn with the path to write the data to.

Then we call getObject to get the object by the bucket and key.

And we call createReadStream to read the file and call pipe to pipe the file to the file write stream to write it.

Categories
JavaScript Answers

How to use global variable in Node.js?

To use global variable in Node.js, we create a module.

For instance, we write

module.exports = new Logger(customConfig);

in logger.js to export the Logger object.

Then we write

const logger = require("./logger");
logger.log("foo");

in app.js to call require to import the logger.js module and call logger.

Categories
JavaScript Answers

How to clone an object with Node.js?

To clone an object with Node.js, we use the Lodash clone method.

For instance, we write

const _ = require("lodash");

const objects = [{ a: 1 }, { b: 2 }];
const cloned = _.clone(objects);

to call clone to clone the objects array and return the clone.