Categories
JavaScript Answers

How to fix Module not found: Error: Can’t resolve ‘crypto’ with JavaScript?

To fix Module not found: Error: Can’t resolve ‘crypto’ with JavaScript, we add the crypto to the browser section of package.json.

For instance, we write

{
  //...
  "browser": {
    "crypto": false
  }
  //...
}

in package.json to disable the crypto module in the browser environment by setting crypto to false.

Categories
JavaScript Answers

How to send image files as API response with Node Express?

To send image files as API response with Node Express, we call res.sendFile.

For instance, we write

app.get("/report/:chart_id/:user_id", (req, res) => {
  //...
  res.sendFile(filePath);
});

to call res.sendFile with the filePath to return the image at the filePath as the response.

Categories
JavaScript Answers

How to accept form data request with Node Express.js?

To accept form data request with Node Express.js, we use the body-parser module.

For instance, we write

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

to call bodyParser.urlencoded to add a middleware to accept form data requests.

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
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