Categories
JavaScript Answers

How to run Mocha tests with extra options or parameters with JavaScript?

To run Mocha tests with extra options or parameters with JavaScript, we get the values from process.argv.

For instance, we write

const argv = require("minimist")(process.argv.slice(2));
console.log("config", argv.config);

to get the command args with process.argv in the Mocha test file.

We then parse it with the minimist library into an object and get the config config.

Then we run the test with

mocha test.js --config=VALUE
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.