Useful file operations in nodejs (Part-1)


Introduction

Nowadays every respectable programming language does have the funtionality of performing simple File I/O operations. In the same way Node.js ,the current talk of the town , is also not far away i.e. Node.js also gives the functionality of File I/O by providing wrappers around the standard POSIX functions.

In Node.js, File I/O methods can be performed in both synchronous as well as asynchronous form depending upon the user requirements. In order to use this module we need to require the  fs   as shown below :

		        
var fs = require('fs');
                
	            

Now we are ready to start performing the file operation using our coding skills.


fs.writeFile

Let's start by creating a simple text file and adding some content in it.


		        
// Name of the file  : message.txt ; 
// Content in the file : Hello Node.js
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
	if (err) 
		throw err;
	console.log('It\'s saved!');
}
// To check it's asynchronous nature !
console.log("This method is Asynchronous");
                
	            

The output of the above code is :


		        
>node file.js
This method is Asynchronous
It's saved!

				
	            

The above mentioned method is asynchronous which is clearly understood by the output of the code.In asynchronous methods , the first argument is always the exception and the last argument is always the callback.


fs.writeFileSync

It is synchronous versions of  fs.writeFile   . The Functionality is similar i.e. It also create a file and writes content in it.


		        
// Name of the file  : content.txt ; 
// Content in the file : This is content
fs.writeFileSync('content.txt', 'This is content');
console.log('File Created and data saved');
// To check it's synchronous nature !
console.log("This method is synchronous");
                
	            

The output of the above code is :


		        
>node file.js
File Created and data saved
This method is synchronous

				
	            

The above mentioned method is synchronous and it will block the execution of program until the file is created and content is added into it.While using synchronous methods , exceptions are throwed instantaneously and in order to avoid it we can use it in a try/catch block. Moreover it is not recommended to use synchronous methods unless no other choice is left because it will block all other processes and halt all connections until it's execution is not done.


fs.readFile

It is used to read file Asynchronously.


		        
//  you have to pass the Relative path of the file from the Current working directory.
// err :  It will handle the exceptions.
// data : it contains the content of the file.
fs.readFile('content.txt', (err, data) => {
	if (err) 
		throw err;
		
	console.log("The Content of the FILE is : " + data);
});

// To check it's Asynchronous nature !
console.log("This method is Asynchronous");
                
	            

The output of the above code is :


		        
>node file.js
This method is Asynchronous
The Content of the FILE is : This is Content
				
	            

fs.readFileSync

It is used to read file Synchronously.


		        
//  you have to pass the Relative path of the file from the Current working directory.
// data : it contains the content of the file.
fs.readFileSync('/Nodejsera/website/nodejs/content.txt');

console.log("The Content of the FILE is : " + data);

// To check it's Synchronous nature !
console.log("This method is Synchronous");
                
	            

The output of the above code is :


		        
>node file.js
The Content of the FILE is : This is Content
This method is Synchronous
				
	            

fs.unlink

It is used to Delete files Asynchronously.


		        
//  you have to pass the Relative path of the file from the Current working directory.
// err :  It handle the exceptions.
fs.unlink('/tmp/data.txt', (err) => {
	if (err) 
		throw err;
	console.log('File /tmp/data.txt deleted successfully');
});
// To check it's Asynchronous nature !
console.log("This method is Asynchronous");
                
	            

The output of the above code is :


		        
>node file.js
This method is Asynchronous
File /tmp/data.txt deleted successfully
				
	            

fs.unlinkSync

It is used to Delete files Synchronously.


		        
//  you have to pass the Relative path of the file from the Current working directory.
fs.unlink('/tmp/data.txt');
console.log('File /tmp/data.txt deleted successfully');

// To check it's Synchronous nature !
console.log("This method is Synchronous");
                
	            

The output of the above code is :


		        
>node file.js
File /tmp/data.txt deleted successfully
This method is Synchronous
				
	            

Summary
We have learned the following :
  • Introduction to filesystem in node.js
  • fs.writeFile
  • fs.writeFileSync
  • fs.readFile
  • fs.readFileSync
  • fs.unlink
  • fs.unlinkSync