Categories
JavaScript Answers

How to fix the “Failed to compile. Module not found: Can’t resolve ‘react-router-dom'” error with JavaScript?

To fix the "Failed to compile. Module not found: Can’t resolve ‘react-router-dom’" error with JavaScript, we install the react-router-dom package.

To install it, we run

npm i react-router-dom

Then we install its type definitions with

npm i @types/react-router-dom
Categories
JavaScript Answers

How to scroll down until you can’t anymore with JavaScript Puppeteer?

To scroll down until you can’t anymore with JavaScript Puppeteer, we use a while loop.

For instance, we write

await page.evaluate(async () => {
  let scrollPosition = 0;
  let documentHeight = document.body.scrollHeight;

  while (documentHeight > scrollPosition) {
    window.scrollBy(0, documentHeight);
    await new Promise((resolve) => {
      setTimeout(resolve, 1000);
    });
    scrollPosition = documentHeight;
    documentHeight = document.body.scrollHeight;
  }
});

to call page.evaluate with a callback that uses a while loop to scroll down until the documentHeight is bigger than scrollPosition.

We call scrollBy to do the scrolling down the page.

When documentHeight is bigger than scrollPosition than we can’t scroll anymore.

Categories
JavaScript Answers

How to request the Garbage Collector in node.js to run with Node.js?

To request the Garbage Collector in node.js to run with Node.js, we call the global.gc method.

For instance, we write

try {
  global?.gc?.();
} catch (e) {
  console.log("`node --expose-gc index.js`");
  process.exit();
}

to call global.gc to request the garbage collector if it’s available.

We make the garbage collection available with the --expose-gc flag.

Categories
JavaScript Answers

How to listen to All Emitted Events in Node.js?

To listen to All Emitted Events in Node.js, we create our own Emitter class.

For instance, we write

class Emitter extends require("events") {
  emit(type, ...args) {
    console.log(type + " emitted");
    super.emit(type, ...args);
  }
}

to create the Emitter class that inherits from the events constructor.

And we add our own emit method to get the event type and call super.emit to emit the event.

Categories
JavaScript Answers

How to convert CSV to JSON in Node.js?

To convert CSV to JSON in Node.js, we use the csvtojson module.

We install it by running

npm install --save csvtojson@latest

Then we use it by writing

const csv = require("csvtojson");

const jsonArrayObj = await csv().fromFile(csvFilePath);
console.log(jsonArrayObj);

to call fromFile to read the csv file into an JSON array.

Then we use await to get the JSON array of objects from the returned promise.