Categories
JavaScript Answers

How to serve static files on a dynamic route using Node Express?

To serve static files on a dynamic route using Node Express, we call the sendFile method.

For instance, we write

app.get("/user/:uid/files/*", (req, res) => {
  const uid = req.params.uid;
  const path = req.params[0] ? req.params[0] : "index.html";
  res.sendFile(path, { root: "./public" });
});

to call app.get to add a get route that gets the URL parameters from req.params.

And we use that to create the path for the file.

Then we call res.sendFile to send the file at the path within the root folder as the response.

Categories
JavaScript Answers

How to create a pair private/public keys using Node.js crypto?

To create a pair private/public keys using Node.js crypto, we call the generateKeyPair function.

For instance, we write

const { generateKeyPair } = require("crypto");

generateKeyPair(
  "rsa",
  {
    modulusLength: 4096,
    publicKeyEncoding: {
      type: "spki",
      format: "pem",
    },
    privateKeyEncoding: {
      type: "pkcs8",
      format: "pem",
      cipher: "aes-256-cbc",
      passphrase: "top secret",
    },
  },
  (err, publicKey, privateKey) => {
    //...
  }
);

to call generateKetPair with 'rsa' to generate a pair of public and private keys.

We set the cipher and passphrase for the private key.

And we set the format for both keys.

Then we get the public and private key from the publicKey and privateKey parameters in the callback.

Categories
JavaScript Answers

How to do server-side browser detection with Node.js?

To do server-side browser detection with Node.js, we get the user-agent request header.

For instance, we write

const ua = request.headers["user-agent"];
let browser;
if (/firefox/i.test(ua)) {
  browser = "firefox";
} else if (/chrome/i.test(ua)) {
  browser = "chrome";
} else if (/safari/i.test(ua)) {
  browser = "safari";
} else if (/msie/i.test(ua)) {
  browser = "msie";
} else {
  browser = "unknown";
}

to call test with various regex to check the user agent string.

We get the user-agent request header with request.headers["user-agent"].

We use the i flag to check each string in a case insensitive manner.

Categories
JavaScript Answers

How to watch directory for changes with nodemon?

To watch directory for changes with nodemon, we use the --watch option.

For instance, we run

nodemon --watch src server.js

to use the --watch option to watch the src folder for changes when running server.js.

Categories
JavaScript Answers

How to listen all interfaces instead of localhost only with Node Express app server?

To listen all interfaces instead of localhost only with Node Express app server, we call listen with '0.0.0.0'.

For instance, we write

const express = require("express");
const app = express();
app.listen(3000, "0.0.0.0");

to call app.listen with "0.0.0.0" to listen for all interfaces at port 3000.