The Node.js filesystem module is used for working with the filesystem on your computer. To include the filesystem module you need to import the module by using require().

const fs = require('fs');


1. File Reading:
For reading there are two common methods i.e. fs.readdir() and fs.readFile(). fs.readdir() is use to read the content of the directory and the callback of this method will return the array of filenames in the directory wheread fs.readFile()is use to read the files on your computer.

const fs = require('fs');

// reading dir
fs.readdir('./', (err, content) => {
    if (err) return err;
    console.log(content);
});

// reading file
fs.readFile('./global.html', 'UTF-8', (err, content) => {
    if (err) return err;
    console.log(content);
});


2. File Writing: The filesystem module has two most common methods which is used for creating files i.e. fs.writeFile() and fs.appendFile(). The fs.appendFile() method appends content to a file. If the file does not exist, the file will be created whereas in the case of fs.writeFile()everytime data will be truncated first.

const fs = require('fs');

// write file
fs.writeFile('./test-area/data.html', 'This file has just been created.', 'utf8', (err) => {
    if (err) return err;
    console.log('The file has been saved.');
});

// append file
fs.appendFile('./test-area/data.html', ' Extra Data has been appended.', 'utf8', (err) => {
    if (err) return err;
    console.log('File has been appended.');
});


3. Creating Directories/Files: fs.mkdir() is used for creating the directory in the filesystem. Below I am combining all the three methods together so that you will get the better understanding of the filesystem module.

const fs = require('fs');

if (!fs.exists('./test-area/test1')) { // checking whether directory exists or not
    fs.mkdir('./test-area/test1', (err) => { // directory created
        if (err) return err;
        fs.writeFile('./test-area/test1/1.txt', 'This is new directory and data.', (err) => { // file created
            if (err) return err;
            console.log('Directory and File has been created.');
        });
    });
}


4. File Removing: As the name clearly signifies that these method is used for removing the files/directories. fs.unlink() is use to remove the files whereas fs.rmdir()is use for removing the directories.

const fs = require('fs');

// removing file
fs.unlink('./test-area/test1/1.txt');

// removing directory
fs.rmdir('./test-area/test1');


5. File Renaming: This method is use for renaming the files.

const fs = require('fs');

// renaming file synchronously
fs.renameSync('./test-area/data.html', './test-area/test1.txt');

// renaming file asynchronously
fs.rename('./test-area/data.html', './test-area/test1.txt', callback);

Last Modified: 2 years ago