Home
Tools
Workshops
Technologies
Pricing
Contact Us



Essentials of Node.js

Part-5 Node.js File Input Output

Brief Introduction
In this tutorial on Node.js File-System, we'll actually start with a brief discussion of Blocking vs Non-Blocking code and then we'll look at both sync and async methods of reading and writing files in node.js.
Blocking vs Non-Blocking Code
One of the features which distinguishes Node.js is that it uses non-blocking code. Let's understand by looking at the difference between Blocking and Non-Blocking code. So what're the scenarios where the code can go blocking:
  1. Calling some REST API and waiting for results.
  2. Writing some data to a DB
  3. Reading data from a file on FileSystem
  4. Writing data to a file on FileSystem
We'll take example of reading a file. Following image gives a scenario of how blocking and non-blocking code would work to read a file and print contents on the console.
As shown in the image, whereas synchronous code block the flow until the contents of the file are read fully the asynchronous code simply assigns a callback cb() which is called when the contents are ready and meanwhile the program flow continues with other tasks that follow. In this way asynchronous code doesn't block the program flow.
We'll now look at file read and write example using both sync and async techniques.
Writing to a File [Sync]
So we'll start by writing some data to a file in Sync mode. In Node.js, fs is the module which is required for file system operations. fs is not a global module, so we'll need to use operator require in order to use fs in our program. You can copy the following code and save it as FileSyncWrite.js

/**

		@name:        FileSyncWrite.js
		@description: A Simple Program to write data to a file synchronously. 
		@author: 	  @rishabhio
 
*/
var fs = require('fs');				// for all modules except global modules, we need to use "require"

var date1 = new Date();
var time_start = date1.getTime();
console.log("starting at: " + time_start);
console.log("ready to write file");
fs.writeFileSync('myfirstfile.txt','Hello World of Synchronous Nodejs');
console.log('finished writing!');
console.log('other task 1');		// just to understand when this is actually executed in sync mode. 
console.log('other task 2');

var date2 = new Date();
var time_end = date2.getTime();
console.log("finishing at: " + time_end);
var execution_time = time_end - time_start;
console.log("Time for execution: " + execution_time );
	
Execution of above program.


you@yourpc ~
$ node FileSyncWrite.js
starting at: 1469692559399
ready to write file
finished writing!
other task 1
other task 2
finishing at: 1469692559423
Time for execution: 41

you@yourpc ~
$ ls           // ls for linux and dir for windows
myfirstfile.txt    // when you do ls or dir you should see myfirstfile.txt there. 
	
Writing to a File [Async]
Now let's write to a file using the Async Mode.

/**
		@name:        FileAsyncWrite.js
		@description: A Simple Program to write data to a file asynchronously. 
		@author: 	  @rishabhio
*/
var fs = require('fs');

var date1 = new Date();
var time_start = date1.getTime();
console.log("starting at: " + time_start);
console.log("ready to write file");

fs.writeFile('mysecondfile.txt','hello world! I am now in async universe',function(error){
	console.log('finished writing!');
});

console.log('other task 1');		// just to understand when this is actually executed in sync mode. 
console.log('other task 2');

var date2 = new Date();
var time_end = date2.getTime();
console.log("finishing at: " + time_end);
var execution_time = time_end - time_start;
console.log("Time for execution: " + execution_time );
	
	


you@yourpc ~
$ node FileAsyncWrite.js
starting at: 1469693223513
ready to write file
other task 1
other task 2
finishing at: 1469693223540
Time for execution: 27
finished writing!
	
Comparison of Sync vs Async
Note in the above 2 outputs, In case of of Async, finished writing is printed to console after all the other tasks have been done, which is not the case in sync operation.
Following are code snippets for sync and async read operations of the files we wrote above.

/**

		@name:        FileSyncRead.js
		@description: A Simple Program to read data from a file synchronously. 
		@author: 	  @rishabhio
 
*/

var fs = require('fs');
console.log('performing read operation');
var contents = fs.readFileSync('myfirstfile.txt');
console.log('Data: ' + contents);
console.log('Moving on to next Task');



/**

		@name:        FileASyncRead.js
		@description: A Simple Program to read data from a file asynchronously. 
		@author: 	  @rishabhio
 
*/

var fs = require('fs');
console.log('performing async read operation');
fs.readFile('mysecondfile.txt',function(error,data ){
	console.log('Data: ' + data);
});
console.log('Moving on to next Task');

You can access all the source code files of this tutorial on GITHUB






developed & nourished with by rishabh.io