Categories
JavaScript Answers

How to change Express view folder based on where is the file that res.render() is called with Node.js?

To change Express view folder based on where is the file that res.render() is called with Node.js, we call the res.render method with the template path.

For instance, we write

app.get("/your/path", (req, res) => {
  res.render(__dirname + "/folder/with/views/viewname");
});

to call res.render with the path to the template as in the route handler for the /your/path route.

Categories
JavaScript Answers

How to call a JSON API with Node.js?

To call a JSON API with Node.js, we install axios.

To install it, we run

npm install axios

Then we use it by writing

const { data } = await axios.post(url, {
  auth: {
    username,
    password,
  },
});

to call axios.post to make a post request to the url with the 2nd argument as the JSON payload.

Then we get the response body from the data property of the object returned by the promise.

Categories
JavaScript Answers

How to detect if argument is array instead of object with Node.js?

To detect if argument is array instead of object with Node.js, we call the util.isArray method.

For instance, we write

const util = require("util");

const isArray = util.isArray([]);
const isArray2 = util.isArray(Array(55));

to call isArray with the value we want to check if it’s an array.

isArray should return true for both since both arguments are arrays.

Categories
JavaScript Answers

How to let others on a local network, access my Node.js app while it’s running on a machine?

To let others on a local network, access my Node.js app while it’s running on a machine, we call listen with the IP address of the computer

For instance, we write

server.listen(3000, "192.168.0.3");

to call listen with the IP address of the computer that the server is running on to allow external connections on port 3000.

Categories
JavaScript Answers

How to encrypt data that needs to be decrypted in Node.js?

To encrypt data that needs to be decrypted in Node.js, we use the crypto module.

For instance, we write

const crypto = require("crypto");
const assert = require("assert");

const algorithm = "aes256";
const key = "password";
const text = "I love kittens";

const cipher = crypto.createCipher(algorithm, key);
const encrypted = cipher.update(text, "utf8", "hex") + cipher.final("hex");

const decipher = crypto.createDecipher(algorithm, key);
const decrypted =
  decipher.update(encrypted, "hex", "utf8") + decipher.final("utf8");

to create a cipher with createCipher.

Then we call cipher.update to encrypt the text string.

Next, we call createDecipher with the same algorithm and key we call createCipher with.

The we call decipher.update to decrypt the encrypted string.