NodeJS - File System Modules

by Devansh


Posted on 09 Aug 2018 12:08:53 (1 month ago)



In this section, I am showing the most common used NodeJS File System Modules Functions. Hope this will help all the beginners. So, in the beginning you need to import the module and assign this to variable so that you can use all its properties. So, as you see all the below code you will notice that I am requiring 'fs' module in each section.

1. File Reading

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

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

const fs = require('fs');

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


4. File Removing

const fs = require('fs');

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

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


5. File Renaming

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);