Node.js in Action: Read Simple Text File Using fs Module

This is the Node.js in action article series. In this article series we will learn various practical examples with code snippets of Node.js.

In our previous article we saw how to implement a simple HTTP server using node.js and implemented a simple countdown example. You can read them here.

This article shows how to work with the “fs” module in node.js. Now, if you don't have a basic understanding of modules in node.js then I request you to go through some practical examples of modules before starting with the “fs” module.

Here is a one line definition for your idea. The module is nothing but a sub part of the application, very often it's a .js file containing a few lines of code.

The "fs" or file system module comes by default with the default node package. It's used to manipulate the file system in the server. Like reading a file, writing to a file, renaming, deleting and much more.

At first we will implement a small example that will read a text file from the server directory. Have a look at the following code.

var http = require('http');

var fs = require('fs');

var server = http.createServer(function (req, res) {

    fs.readFile("simple.txt", "utf8", function (error, data) {

        console.log(data);

    });

});

server.listen(9090);

console.log('server running...')

The line:

var fs = require('fs');

Will create one variable containing an instance of  the “fs” module using the “require()” function.

Once we initialize the module we will be able to access any function of this module using the “fs” variable. In this example we are calling the readFile() function defined in the “fs” module to read the contents of the text file as in the following:

fs.readFile("simple.txt", "utf8", function (error, data) {
console.log(data);
});

It takes three parameters as arguments, the first parameter is the file name. In this example I have created the “simple.txt” text file and kept it in a sample location of my server code.

The second argument is the “encoding scheme” for my file and the third argument is an anonymous callback function, that will execute when the file read operation finishes.

Within the callback function we are logging the content data to the console. So, once we have run the application and it is our HTTP server, we should see the file contents in the console. So, let's run the application.

I will use a command prompt to run my server.

command prompt

Here it is up and running, now let's make one HTTP request to the server using a browser.

running

And we got the contents of text file in the console. Fine; now let's improve the example a little bit. Here is our modified code.
 

var http = require('http');

var fs = require('fs');

var server = http.createServer(function (req, res) { 

    var fileName = 'simple.txt'

    fs.exists(fileName, function (exists) {

        if (exists) {

            fs.stat(fileName, function (error, stats) {

                fs.open(fileName, "r", function (error, fd) {

                    var buffer = new Buffer(stats.size);

 

                    fs.read(fd, buffer, 0, buffer.length, null, function (error, bytesRead, buffer) {

                        var data = buffer.toString("utf8", 0, buffer.length);

                        console.log(data);

 

                        fs.close(fd);

                    });

                });

            });

        }

    });  

});

server.listen(9090);

console.log('server running...')

We have just implemented few best practices in this example, like checking for the existence of the file before reading it, then we are opening the file in read mode and after reading it, we are closing it properly. In this case I have changed the contents of the “simple.text” file a little bit. Once we have run this code, in the console we will see the following output.

output

Conclusion

In this simple example we have learned how to read a simple text file using node.js. I hope you have understood it. In future articles of this series we will understand few more examples of the “fs” module.

Up Next
    Ebook Download
    View all
    Learn
    View all