File System module is used to perform all file related operations in Node JS like,

1. Read data from the file.

2. Write data into the file.

3. Append the data into the file.

4. Delete the file.

5. Changes the permission of the file, etc.

Node JS used fs module to perform all the File System operations.

To use this module:

const fs = require('fs');

All file system operations have synchronous, callback, and promise-based forms.

Synchronous example


The synchronous form blocks the Node.js event loop and further JavaScript execution until the operation is complete. Exceptions are thrown immediately and can be handled using try…catch, or can be allowed to bubble up.

const fs = require('fs');

try {
  fs.unlinkSync('/tmp/hello');
  console.log('successfully deleted /tmp/hello');
} catch (err) {
  // handle the error
}

Callback example


The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument is null or undefined.

const fs = require('fs');

fs.unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

Promise example


Promise-based operations return a Promise that is resolved when the asynchronous operation is complete.

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

(async function(path) {
  try {
    await fs.unlink(path);
    console.log(`successfully deleted ${path}`);
  } catch (error) {
    console.error('there was an error:', error.message);
  }
})('/tmp/hello');