Categories
JavaScript Answers

How to add Express.js response timeout with Node.js?

To add Express.js response timeout with Node.js, we use the connect-timeout module.

For instance, we write

const timeout = require("connect-timeout");

const haltOnTimedout = (req, res, next) => {
  if (!req.timedout) {
    next();
  }
};

app.use(timeout(120000));
app.use(haltOnTimedout);

to add the halfOnTimedout function.

In it, we check if the request timed out with req.timedout.

If it’s false, then we call next to call the next middleware.

Then we call app.use to add the timeout middleware to make requests time out after 120000ms.

And we call app.use again to add the haltOnTimedout middleware.

Categories
React Answers

How to detect whether input element is focused within React?

To detect whether input element is focused within React, we check the activeElement property.

For instance, we write

//...
const Component = () => {
  const searchInput = React.useRef(null);
  //...
  if (document.activeElement === searchInput.current) {
    // do something
  }

  return <input type="text" ref={searchInput} />;
};

to create a ref with useRef and assign it to the input.

Then we check if the input is focused with document.activeElement === searchInput.current.

document.activeElement is the element currently focused on and searchInput.current is the input with the ref.

Categories
JavaScript Answers

How to install NodeJS LTS on Windows as a local user without admin rights?

To install NodeJS LTS on Windows as a local user without admin rights, we download the zip file and then add the Node.js folder to the PATH environment variable.

To do this, we:

  1. Download the node.js LTS binary for Windows and extract it to your desired location

2.Add the path of the nodejs folder to the PATH environment variable: (Shortcut winkey+R and enter: rundll32 sysdm.cpl,EditEnvironmentVariables)

  1. Open a new command window (winkey+R and type cmd)

  2. Type node -v and npm -v to verify the installation

Categories
JavaScript Answers

How to set navigation timeout with Node.js Puppeteer?

To set navigation timeout with Node.js Puppeteer, we set the timeout option.

For instance, we write

await page.goto(url, { waitUntil: "load", timeout: 0 });

to call goto to go to the url.

We set timeout to 0 milliseconds to remove navigation timeout.

Categories
JavaScript Answers

How to include a partial with Node.js EJS?

To include a partial with Node.js EJS, we use include.

For instance, we write

<%- include('myView.ejs') %>

to use include to include the myView.ejs partial in our template.