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.

Categories
JavaScript Answers

How to get last modified file date in Node.js?

To get last modified file date in Node.js, we use the stats.mtime property.

For instance, we write

fs.stat("/dir/file.txt", (err, stats) => {
  const mtime = stats.mtime;
  console.log(mtime);
});

to call fs.stat to get the file metadata for the /dir/file.txt file.

And we use stats.mtime to get the last modified date.

Categories
JavaScript Answers

How to restart a Node.js server?

To restart a Node.js server, we use the pkill command.

For instance, we run

pkill -HUP node

to kill all Node.js processes with pkill.

Then we start node again.