Node File System Example

Like all other programming language, there is filesystem object in nodejs, which allow developer to handle all file and folder related operations, here are the complete list of node file system objects and methods.

var fs = require('fs');

To work with nodeJs file system object in node application, you need to add above reference in your javascript code, the fs object will allow you to access all methods (synchronous as well as asynchronous) related to file and directory.

file system directory in NodeJs

Here you learn how to work with folder or directory in file system using node js.

In following code, first we check if directory exists in node script then create directory using Nodejs (if that doesn't exist).

var fs = require('fs');
var localDir = './staticfiles1';
if (!fs.existsSync(localDir)){
    console.log("new directory has been created");

We can delete any directory with same file system object (fs).

In following example, we can delete an empty directory, if there is any file or folder inside that, then the below code will throw exception.


What if you want to delete a directory with all child directories and files inside it!

Here is the code below will delete a folder with all child folders and files using nodeJS script.

 // delete directory with all childs inside
function deleteDirectoryWithChilds(folderpath) {
    if (fs.existsSync(folderpath) && 
      fs.readdirSync(folderpath).forEach(function(file, index)
        var curPath = folderpath + "/" + file;
        console.log("curPath: "+ curPath);
        if (fs.lstatSync(curPath).isDirectory())
            // calling the same function again
        } else {
            // delete the file
      console.log(`delete folder "${folderpath}"...`);
// finally calling the function with folder path
    console.log("delete complete");

Notice, to delete any NodeJS file from system, you need to call unlinkSync function like example below


Here is an example of how we can read a text file using node js and log the content.

var fs = require('fs');
fs.readFile('staticfiles/myTextFile.txt', function (err, data) {
    if (err) {
       return console.error(err);
    console.log("Content: " + data.toString());

Instead of using "readFile" we could have also used "readFileSync".

Almost all file system object methods has two form asynchronous and synchronous.

Reading html file and writing in browser

In below example we read one html file from local folder and publish that one browser using node http module.

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
    fs.appendFile('staticfiles/myhom.htm', 'data to append', function (err) {
        if (err) throw err;
  // reading html file and writing in browser
    fs.readFile('staticfiles/myhom.htm', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    return res.end();

You may be intereted to read following posts

Node JS File System
Learn Node application development, free node js framework tutorial with examples.
Node examples | Join JavaScript Course