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.

Categories
JavaScript Answers

How to unit test routes with Express and JavaScript?

To unit test routes with Express and JavaScript, we use supertest.

For instance, we write

describe("GET /users", () => {
  it("respond with json", (done) => {
    request(app)
      .get("/users")
      .set("Accept", "application/json")
      .expect(200)
      .end((err, res) => {
        if (err) return done(err);
        done();
      });
  });
});

to call request with app to use the Express app to make requests.

Then we call get to make a get request to the /users route.

We call set to set the request header.

We call expect to check that the status code returned is 200.

And we call end with a callback that calls done to finish the test.

The test passes if done is called with no argument.

Categories
JavaScript Answers

How to add dates to pm2 error logs with JavaScript?

To add dates to pm2 error logs with JavaScript, we add the --lof-date-format option.

For instance, we run

pm2 start app.js --log-date-format 'DD-MM HH:mm:ss.SSS'

to set the --log-date-format to the date format we want for the log entry date to include the date in each log entry.