Categories
JavaScript Answers

How to use FormData in Node.js without browser?

To use FormData in Node.js without browser, we use the URLSearchParams constructor.

For instance, we write

const fs = require("fs");

const form = new URLSearchParams();
form.append("my_field", "my value");
form.append("my_buffer", new Buffer(10));
form.append("my_file", fs.createReadStream("/foo/bar.jpg"));

to create a URLSearchParams object.

Then we call append with the key and value of each form data entry to add it.

We can add buffers and read streams for binary data.

Categories
JavaScript Answers

How to fix JSON.parse(fs.readFileSync()) returning a buffer with Node?

To fix JSON.parse(fs.readFileSync()) returning a buffer with Node, we specify the encoding.

For instance, we write

const squadJSON = JSON.parse(fs.readFileSync("file.json", "utf8"));

to call readFileSync to open the file.json file.

We specify the encoding is 'utf8' to return a Unicode string instead of a buffer.

Categories
JavaScript Answers

How to make Node pm2 log to console?

To make Node pm2 log to console, we call connect.

For instance, we write

const pm2 = require("pm2");

pm2.connect((err) => {
  if (err) {
    console.error(err);
    process.exit(2);
  }
  pm2.start(
    [
      {
        script: "server.js",
        output: "/dev/stdout",
        error: "/dev/stderr",
      },
    ],
    (err, proc) => {
      if (err) {
        throw err;
      }
    }
  );
});

to call connect with a callback that calls start with some options.

We set output to the location to '/dev/stdout' to log to the console.

And we log errors to '/dev/stderr' by setting error to "/dev/stderr".

Categories
JavaScript Answers

How to use Node Mongoose Find with multiple conditions?

To use Node Mongoose Find with multiple conditions, we put all the conditions in one object.

For instance, we write

User.find(
  { $or: [{ region: "NA" }, { sector: "Some Sector" }] },
  (err, user) => {
    if (err) {
      res.send(err);
    }
    console.log(user);
    res.json(user);
  }
);

to call find with an object with $or set to an array of conditions we’re looking for.

And we get the result from user in the callback.

Categories
JavaScript Answers

How to fix Error: Failed to launch the browser process with Node Puppeteer?

To fix Error: Failed to launch the browser process with Node Puppeteer, we call launch with the browser path.

To fix this, we run

sudo apt-get install chromium-browser

to install the Chromium browser.

Then we write

const browser = await puppeteer.launch({
  executablePath: "/usr/bin/chromium-browser",
});

to call launch with an object with the executablePath set to the Chromium browser path to start it.