Using the File System module (‘fs’) in Node.js

OpenJavaScript 0

Last updated: September 27, 2022.

When running JavaScript in Node.js, you have access to the file system.

You can access it using the File System Module. This is a core Node module, which means that it is available in Node by default without the need for separate installation.

Table of contents

Importing the File System Module

To make the File System Module available in your project, include the following at the top of your script:

const fs = require('fs');

The necessary methods to work with the file system are now available in fs.

Below are some of the most useful methods you now have available to you for working with the file system:

  • fs.readFile(): reads the contents of a file
  • fs.writeFile(): write data to a file
  • fs.appendFile(): append data to a file
  • fs.access(): check if a file exists and its accessibility
  • fs.mkdir(): create a new directory
  • fs.rename(): rename a file or directory
  • fs.rmdir(): remove a directory
  • fs.watchFile(): observe for change to a file

Each method is asynchronous by default. This can be good for workflow efficiency because JavaScript will continue processing the rest of your script while waiting.

But, if you want JavaScript to wait for a method to complete, each method has a synchronous equivalent that can be accessed under its name plus ‘Sync‘. So, for example, the synchronous version of readFile is readFileSync.

A comprehensive list of available methods is available in Node.js documentation.

Usage examples

Writing a file

As first and second arguments, writeFile accepts the name of the new file and the data it will contain.

As a third argument, it accepts a callback function. This function is fired when the file has been (or has failed to be) created. To check for an error, pass the error object into an if statement:

const fs = require('fs');

fs.writeFile('testFile.txt', 'Created with Node.js!', function(error) {
  if (error) {
     console.log("Failed to create file!");
     return error;
  }
  console.log("File created successfully!");
});

Using writeFileSync, there is no callback function. Instead, you attempt to write the file in a try block and catch any error in a catch block:

const fs = require('fs');

try {
  fs.writeFileSync('testFile.txt', 'Created with Node.js!');
  console.log("File created successfully!");
} catch(error) {
  console.log("Failed to create file!");
}

Reading a file

You can read a file from the system using the readFile method.

As a first and second argument, it accepts the file to read and encoding. If no encoding is specified, UTF-8 is assumed.

The next argument is a callback function, which runs when an attempt to read the file is complete. Use the error parameter to check for an error and then handle the data:

const fs = require('fs');

fs.readFile('testFile.txt', 'utf8', function (error, data) {
  if (error) {
     console.log("Failed to read file!");
     return error;
  }
  console.log(data);
});

Using readFileSync, a try...catch statement is used instead of the callback pattern:

const fs = require('fs');

try {
  const data = fs.readFileSync('testFile.txt', 'utf8');
  console.log(data);
} catch(error) {
  console.log("Failed to read file!");
}

Check if a file exists

You can check if a file exists using the access method.

In the second parameter position, you pass in a constant from fs. You can check if the file exists (F_OK), is readable (R_OK) or writable (W_OK).

For example:

const fs = require('fs');

fs.access('testFile.txt', fs.constants.F_OK, function(error) {
  if (error) {
    console.log("The file does not exist");
  }
  console.log("The file exists");
});

And here is how you would do it synchronously:

const fs = require('fs');

try {
  fs.accessSync('testFile.txt', fs.constants.F_OK);
  console.log("The file exists");
} catch(error) {
  console.log("The file does not exist");
}

The fs/promises API

Alternatively, you can use the promise-based fs/promises API to work with the file system:

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

async function readMyFile() {
  try {
    const data = await fs.readFile('testFile.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.log(err);
  }
}
readMyFile();

Related links