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.

Categories
JavaScript Answers

How to fix npm install hangs on loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree?

To fix npm install hangs on loadIdealTree:loadAllDepsIntoIdealTree: sill install loadIdealTree, we remove the package.json file.

To fix this, we remove the package.json file and then run

npm install

to install all packages again.

Categories
JavaScript Answers

How to broadcast messages on a namespace with Node socket.io?

To broadcast messages on a namespace with Node socket.io, we call broadcast.emit.

For instance, we write

chat.on("connection", (socket) => {
  socket.on("message", (msg) => {
    socket.emit(msg);
    socket.broadcast.emit(msg);
  });
});

to call broadcast.emit to broadcast the msg string to all clients.