Categories
JavaScript Answers

How to add line breaks in Node Jade?

To add line breaks in Node Jade, we add a br element.

For instance, we write

p.
    Some text on the first line.#[br]
    Some text on the second line.

to add the br element with #[br].

Categories
JavaScript Answers

How to prevent XSS in Node.js?

To prevent XSS in Node.js, we use the validator module.

For instance, we write

const validator = require("validator");

const escapedString = validator.escape(someString);

to call validator.escape with someString to return an escaped version of someString.

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.