Ways Of Dealing with File System (fs) in Node.js

Ways Of Dealing with File System (fs) in Node.js

A file is a sequence of bits. we have three different ways to do the same exact thing in nodejs using the file system "fs". We could use:

Promises API (Async)

Callback API (Async)

Synchronous API

const fs = require("fs/promises");

// ******* Promise API ********* //

(async () => {
  try {
    await fs.copyFile("text.txt", "copied-promise.txt");
  } catch (error) {
    console.log(error);
  }
})();

// ******* Callback API ********* //
// Best and fastest way
const fs = require("fs");

fs.copyFile("text.txt", "copied-promise.txt", (error) => {
  if (error) {
    console.log(error);
  }
});

// ******* Synchronous API ********* //

const fs = require("fs");
fs.copyFileSync("text.txt", "copied-promise.txt");

So we can copy or delete or create ... file using one of them so we have these three ways of doing the same thing.

import { watch } from "node:fs";
// Example when handled through fs.watch() listener
// Callback Api
watch("./tmp", { encoding: "buffer" }, (eventType, filename) => {
  if (filename) {
    console.log(filename);
    // Prints: <Buffer ...>
  }
});


// Promises Api
const fs = require("fs/promises");

(async () => {
  const watcher = fs.watch("./");

  for await (const event of watcher) {
    console.log(event); // { eventType: 'change', filename: 'app.js' }
  }
})();