Categories
JavaScript Answers

How to inherit from the EventEmitter class with Node.js?

To inherit from the EventEmitter class with Node.js, we use the extends keyword.

For instance, we write

const EventEmitter = require("events");

class MyEmitter extends EventEmitter {
  // ...
}

const myEmitter = new MyEmitter();
myEmitter.on("event", () => {
  console.log("an event occurred!");
});
myEmitter.emit("event");

to create the MyEmitter class that inherits from the EventEmitter class.

We add our own methods inside the class.

Then we create a new instance of MyEmitter with new.

We call on to listen to the 'event' event.

And we call emit to emit the 'event' event.

Categories
JavaScript Answers

How to force Yarn to reinstall a package with JavaScript?

To force Yarn to reinstall a package with JavaScript, we delete the node_modules folder and reinstall.

To do this, we delete the node_modules folder and then run

yarn install --check-files

to reinstall all the packages.

Categories
JavaScript Answers

How to get image from web and encode with base64 with Node.js?

To get image from web and encode with base64 with Node.js, we call the axios.get method.

For instance, we write

const axios = require("axios");
//...
const image = await axios.get(url, { responseType: "arraybuffer" });
const raw = Buffer.from(image.data).toString("base64");
const base64Image = "data:" + image.headers["content-type"] + ";base64," + raw;

to call axios.get to get the image from url with a get request.

We get the response as an arraybuffer with { responseType: "arraybuffer" }.

Then we call Buffer.from to convert the arraybuffer to a buffer.

And we call toString with 'base64' to convert it to a base64 string.

Then we put the content type string before the string.

Categories
JavaScript Answers

How to output ‘id’ instead of ‘_id’ with Node.js MongoDB?

To output ‘id’ instead of ‘_id’ with Node.js MongoDB, we call set to modify the toJSON method.

For instance, we write

Schema.set("toJSON", {
  virtuals: true,
});

to call set with an object that sets virtuals to true to change _id to id and return it.

Categories
JavaScript Answers

How to fix cannot enqueue Handshake after invoking quit with Node.js MySQL?

To fix cannot enqueue Handshake after invoking quit with Node.js MySQL, we create a connection pool.

For instance, we write

const mysql = require("mysql");
const pool = mysql.createPool({
  //...
});

pool.getConnection((err, connection) => {
  connection.query("...", (err, rows) => {
    connection.release();
  });
});

to call createPool tro create a connection pool.

Then we call getConnection to get the database connection.

And we call query to make the query with the connection in the callback.

Once we’re done, we call release to release the connection.