A Beginner's Guide to the File System Module in Node.js

A Beginner's Guide to the File System Module in Node.js

·

5 min read

The file system module, or simply fs, enables you to access and interact with the file system on your machine

How to use fs

The file system module is a core Node.js module. You do not have to install it. You only have to import it into your file by adding the following line to the top of your file:

const fs = require('fs');

You also need to import the path module, which is another core Node.js module that allows you to work with file and directory paths. Add the following line to your file, after importing the fs module:

const path = require('path');

Sync vs Async

All fs methods are asynchronous by default. You can use the synchronous version by adding Sync at the end of the method. For example, writeFile becomes writeFileSync

Write to a File

To write to a file from your Node.js application, you use the writeFile method. The writeFile method takes the following arguments at a minimum:

  1. the name of the file

  2. the content

  3. a callback

The specified file's old content is replaced with the content provided as an argument if the file already exists. If the specified file does not exist, it creates a new file.

Asynchronous Example:

fs.writeFile('asyn.txt', "This is an async file", (err) => {
    if (err) {
        console.log('Error while asynchronously writing the file');
    } else {
        console.log("Successfully wrote the async file");
    }
});

Synchronous Example:

try {
    fs.writeFileSync("sync.txt", "This is a sync file");
    console.log('Successfully wrote the sync file');
} catch (err) {
    console.log('Error while writing the sync file');
}

Append to a File

To append to a file from your Node.js application, you use the appendFile method. The appendFile method takes the following arguments at a minimum:

  1. the name of the file

  2. the content to append

  3. a callback

The specified file's content has the new content appended to it if the file exists. If the specified file does not exist, it creates a new file with the specified content.

Asynchronous Example:

fs.appendFile("asyn.txt", "\nNext line: async text", (err) => {
    if (err) {
        console.log('Error while asynchronously appending to the file');
    } else {
        console.log("Successfully appended text to the async file");
    }
});

Synchronous Example:

try {
    fs.appendFileSync("sync.txt", "\nNext line: sync text");
    console.log('Successfully appended text to the sync file');
} catch (err) {
    console.log('Error while appending to the sync file');
}

Read from a File

Before you read from a file, you need to create and store the path to the file. You can create the file path with the join method from the path module, as follows:

const pathName = path.join(process.cwd(),"/asyn.txt")
const pathName2 = path.join(process.cwd(),"/sync.txt")

The first argument, process.cwd(), returns the current working directory.

The readFile method takes two arguments at a minimum:

  1. the path of the file

  2. option

  3. a callback

Asynchronous Example:

fs.readFile(pathName, "utf-8", (err, data) => {
    if (err) {
        console.log("Error while reading the async file");
    } else {
        console.log("Async file data:", data);
    }
});

Synchronous Example:

try {
    const data = fs.readFileSync(pathName2, "utf-8");
    console.log("Sync file data:", data);
} catch (err) {
    console.log("Error while reading the sync file");
}

Delete a File

The file system module has a method that allows you to delete files. Note that it only works for files and not directories.

When you call the unlink and unlinkSync method with the file path as an argument, it deletes the file.

Asynchronous Example:

fs.unlink(pathName2, (err) => {
    if (err) {
        console.log("Error while deleting the file");
    } else {
        console.log("Successfully deleted the file");
    }
});

Synchronous Example:

try {
    fs.unlinkSync(pathName2);
    console.log("File deleted successfully (synchronously)");
} catch (err) {
    console.log("Error while deleting the file");
}

Rename a File or Directory

You can rename directories and files using the fs module. You can do this with the rename method, as shown in the code snippet below.

The rename method takes three arguments:

  1. the first argument is the existing folder/file

  2. the second argument is the new folder/file

  3. a callback

// renaming a directory 
fs.rename(`${process.cwd()}/myFolder/secondFolder`, `${process.cwd()}/myFolder/newFolder`, (err) => { 
if (err) throw err; 
console.log('Directory renamed!') 
}); 

// renaming a file 
fs.rename(`${process.cwd()}/content.txt`, `${process.cwd()}/newFile.txt`, (err) => { 
if (err) throw err; 
console.log('File renamed!') 
});

Sum of all with an example

  • Command-line arguments: The code uses process.argvto capture command-line arguments which dictate the operation (e.g., "read," "delete") and target file.

  • switch statement: A switch statement determines the action based on the 'operation' argument.

const fs = require("fs");
const path = require("path");

const operation = process.argv[2];
const file = process.argv[3];
const content = process.argv[4];

switch (operation) {

  case "read":{
    try{
      let data = fs.readFileSync(file,'utf-8')
      console.log(data)
    }catch(err){
      console.log(err)
    }

    break;
  }

  case "delete":{
    try{
      let data = fs.rmSync(file)
      console.log('File test.txt deleted')
    }catch(err){
      console.log(err)
    }

    break;
  }

  case "create":{
    try{
      let data =  fs.writeFileSync(file,'')
      console.log('File test.txt created')
    }catch(err){
      console.log(err)
    }

    break;
  }

  case "append":{
    try{
      let data =  fs.appendFileSync(content,`\n${file}`)
      console.log('Content appended to the file test.txt')
    }catch(err){
      console.log(err)
    }

    break;
  }

  case "rename":{
    try{
      let data =  fs.renameSync(file,content)
      console.log('File test.txt renamed to new.txt')
    }catch(err){
      console.log(err)
    }

    break;
  }

  default:{
    console.log(`Invalid operation '${operation}'`);
  }
}

Learned something? Hit the ❤️ to say “thanks!” and help others discover this article.

Check out my blog for more things related NodeJS.