File System in Node Js


In this tutorial, we are going to learn about the file system module in Node js by learning about how to create, update, delete and renaming files in it.


What is a File System in Node js?

File System or fs module in allows us to work with the files in node js, we require the file system to perform the most important tasks like reading, writing files or from the files. But the file system isn’t just limited to the writing and reading of the files, there is a lot that can be done with the file system module. Let’s use the file system and learn the read, write, delete and other functions in it.

Importing the File System Module

Since, the file system module is in built module in node js so we don’t have to import it separately through the node package manager (npm); we can simply assign any var or const to the ‘fs’ module and import it by using the ‘require’ method, such as:

var fs = require('fs');

Recommended Books


Reading the File in Node Js

Once you have imported the ‘fs’ module, it is time to create a web server and read an html file through it. You can use any file extension you like, but make sure the ‘fs’ module runs it perfectly. So in our case, we have created a random html file known as html_file.html and read it via ‘fs’ and ‘http’ module. The html contents will be as follows:

file system in node js

Let’s run the file on node js that you will create for reading the file. In our case the file is ‘file.js’:

var http = require('http');
var fs = require('fs');

//creates a server:
http.createServer(function (req, res) {
  fs.readFile('html_file.html', function(err, file) {
  res.writeHead(200, {'Content-Type': 'text/html'}); //write the head of the file as text/html.  
  res.write(file); //Send the response as parameter file
  return res.end() //res.end() will end the response process
  });
}).listen(2020); //the server listens at 2020 port

console.log("Server has started listening at port 2020");

Running ‘file.js’ on terminal or command prompt:

file system in node js

Output on running ‘file.js’ is:

file system in node js






Creating the Files in Node Js

There are a number of ways to create files in node.js, each catering to a specific use and purpose. The three main methods to create files in node js are:

fs.appendFile()

The appendFile method is used for appending file to the file, even if the file isn’t present at the moment, this method will create one, let’s create a file using appendFile() method:

var fs = require('fs');

fs.appendFile('file.txt', 'File Created!', function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
});

As you can see above that we have created a file.txt file and appended ‘File Created’ and if some error occurs then we have created an inside function to return an error message.

Let’s run the file in terminal or command prompt:

creating file in node js

Now let’s see the appended text on the ‘file.txt’ file:

creating file in node js

fs.open()

fs.open() method is used for reading, appending, writing to a file, you can define a flag by yourself, if you haven’t defined a flag then ‘r’ is the default flag. Let’s look at some more flags which are mentioned in detail in official nodejs documentation.

r Used for opening the file by reading through it and shows an error is file isn’t present.
r+ Used for reading and writing the file and shows an error is file isn’t present.
rs+ Used to open file in synchronous mode.
w Used for writing to a file and creates a file if it isn’t present.
wx Same for writing the file but doesn’t work if file isn’t present.
w+ Used for reading and writing to a file and creates a file if it isn’t present.
wx+ Same for reading and writing the file but doesn’t work if file isn’t present.
a Used for appending to a file, and file is created if it isn’t present.
ax Same for appending the file but doesn’t work if file isn’t present.
a+ Used for reading and appending to a file, and file is created if it isn’t present.
ax+ Same for reading and appending the file but doesn’t work if file isn’t present.





fs.WriteFile()

This method is used for replacing content in the existing file. Let’s use this method and replace the existing content of ‘file.txt’:

var fs = require('fs');

fs.writeFile('file.txt', 'I am new content!', function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was created!");
});

Let’s run the file.js on terminal or command prompt now:

write file in node js

Output of the ‘file.txt’ file is:

write file in node js

Updating the Files in Node Js

You can update the files in node js by using the two methods:

fs.appendFile()

The appendFile method is used for appending file to the file, even if the file isn’t present at the moment, this method will create one.

fs.writeFile()

This method is used for replacing content in the existing file and file isn’t present then it creates one.

Deleting Files in Node Js

We can delete a specified file using the fs.unlink() method, let’s look at this method and see how it works:

var fs = require('fs');

fs.unlink('file.txt', function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was deleted!");
});

Running the ‘file.js’ on terminal or command prompt:

deleting a file in node js

You can check in the root directory where ‘file.txt’ was stored, it isn’t there no more.

Renaming Files in Node Js

You can rename a current file by using the fs.rename() method, mainly it includes two arguments the first one is the old file name and the second one is the new file name, let’s see how we can practically do that:

var fs = require('fs');

fs.rename('file.txt', 'newfile.txt', function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was renamed!");
});

Running the ‘file.js’ on terminal or command prompt:

renaming files in node js

You can read more about the file system in detail here