Synchronous & Asynchronous File Handling in NodeJS

File Handling plays an important role in NodeJS. By using this feature, we can access data present in different files present in different locations.

File handling in NodeJS is done by adding ‘fs‘ module in our project. So our first step will be to create an object of type ‘fs‘, which is mentioned below:

var foo = require(‘fs’);

There are basically two types of file handling in Node. First one is Synchronous File Handling. In synchronous file handling each file is processed one by one. Thus, this process takes a lot of time if we have many files to process. But it will be a good idea if we have to process one or two files at a time.

// Synchronous File Handling

Suppose we have a text file named “hello.txt” containing the text “Hello World” & is present in the same directory as our project file. Now, we want to read the contents of hello.txt and output them in a console. Below will be the approach for that.

var greet = foo.readFileSync(__dirname + ‘/hello.txt’, ‘utf8’);

console.log(greet);                    // output: “Hello World”

In the above example, we are storing the content of a hello.txt file in a variable called ‘greet‘ by using the ‘foo‘ object’s property ‘readFileSync‘, which will search for the file and read its content.

__dirname‘ will provide the path of the current directory.

utf8‘ is the standard character encoding and will convert the file content from bytes to standard characters.

 

// Asynchronous File Handling

In this type, all the files will be read by the V8 engine at once and will be placed in a memory heap and later after the code execution is done, all the files will be read one by one so that overall functioning of the program will not be hampered.

Below is the code for asynchronous file processing

var greet2 = foo.readFile(__dirname + ‘hello.txt’, ‘utf8’, function(err, data) {

    console.log(data);             // Output: “Hello World”

});

readFile() is an asynchronous function which will perform processing of the file

The last parameter in the readFile() is the “Error First Callback Function()“, which takes ‘error object’ as its first parameter and if error is not present then it will take ‘null’ as its first parameter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s