Categories
JavaScript Answers

How to redirect user’s browser URL to a different page in Node.js?

To redirect user’s browser URL to a different page in Node.js, we call the Express res.redirect method.

For instance, we write

const express = require("express");
const app = express();

app.get("*", (req, res) => {
  res.redirect("https://www.example.com/");
});

app.set("port", process.env.PORT || 3000);
const server = app.listen(app.get("port"), () => {});

to call res.redirect to redirect to https://www.example.com in the catch get route we created.

Categories
JavaScript Answers

How to get the time of day in JavaScript or Node.js?

To get the time of day in JavaScript or Node.js, we use the date’s getHour method.

For instance, we write

const date = new Date();
const currentHour = date.getHours();

to create a date object with the current date and time with the Date constructor.

And then we call getHours on it to get the current hour of the day.

Categories
JavaScript Answers

How to create a simple http proxy in Node.js?

To create a simple http proxy in Node.js, we use the http-proxy package.

For instance, we write

const http = require("http");
const httpProxy = require("http-proxy");
const proxy = httpProxy.createProxyServer({});

http
  .createServer((req, res) => {
    proxy.web(req, res, { target: "http://www.example.com" });
  })
  .listen(3000);

to call http.createServer to create a web server.

We call it with a callback that calls proxy.web to create a proxy that redirects requests to http://www.example.com

Categories
JavaScript Answers

How to close Node Express server?

To close Node Express server, we call close on the server instance.

For instance, we write

const server = app.listen(3000);
server.close((err) => {
  console.log("server closed");
  process.exit(err ? 1 : 0);
});

to call server.close to close the server.

We call it with a callback that’s called when the server is closed.

Categories
JavaScript Answers

How to set a timeout on a http.request() in Node?

To set a timeout on a http.request() in Node, we call request with an object with the timeout property.

For instance, we write

const options = {
  //...
  timeout: 3000,
};

const request = http.request(options, (response) => {
  // ...
});

request.on("timeout", () => {
  request.destroy();
});

to call request with the options object which has the timeout set to 3000 ms.

We get the response from the callback.

And we listen for the timeout event with on.

In the on callback, we call destroy to stop the request.