File IO in Node JS

 

     In any system, file input output services are a crucial functionality which governs many things. In NodeJS, file IO is required file serving html pages or when you want your client to download some file or even when you create some other tools with NodeJS apart from web servers. Following are some of the file IO methods which are frequently used by developers.

The examples shown consider the following file structure:


The server.js file will hold our code to execute and myTextFile.txt will contain some message which we will read or write to. For file IO, NodeJS provides fs module which included in the NodeJS core modules. You do not need to do npm install for fs module.

myTextFile.txt
Hello..!! I am inside myTextFile.txt                                                                     

Reading a file
The fs module provides 2 functions to read files. One method is synchronous i.e. it runs on the main thread (a blocking operation) and the other one is asynchronous. Here is the basic syntax for using the same:

Synchronous Reading
use strict;
const fs = require(fs);
var readFileMainThread = function(){
   var content = fs.readFileSync(.\myTextFile.txt);
   console.log(content.toString());
};
readFileMainThread();

Asynchronous Reading
use strict;
const fs = require(fs);
var readFileAsync = function(){
   fs.readFile(.\myTextFile.txt, function(err, content){
       console.log(content.toString());
   });
};
readFileAsync();

In both the cases, the content returned is in the form of a buffer. To display the actual content you need to convert this into string. Buffers are the exact bits in which the data is stored in the computer -- in the form of 1s and 0s. When you print a buffer to console, it will show some hexadecimal numbers whose binary representation is how the data is stored on the disk.

Writing a file
Writing is also similar to reading. The fs module provides a synchronous method as well as an asynchronous method to write something to a file.

Synchronous Writing
use strict;
const fs = require(fs);
var writeFileMainThread = function(){
   var content = This is my new content to write to a file;
   fs.writeFileSync(.\myTextFile.txt, content);
};
writeFileMainThread();

Asynchronous Writing
use strict;
const fs = require(fs);
var writeFileAsync = function(){
   var content = This content will also be written to a file. But Asynchronously;
   fs.writeFile(.\myTextFile.txt,content, function(err){
       if(err) //Some error has occured while writing
       else //Successful
   });
};
writeFileAsync();

In both the cases, the first argument to function is the file path to which the content is to be written. If the file does not exists then the file is automatically created. The 2nd argument is the content which is to be written. Here we pass the string instead of buffer (as is returned when reading).

Checking Existence of Files and Folders
Many a times you are saving some dynamic data into file. In such cases if you try to read a non-existing file, your application will crash. To prevent this, it is a  good practise to first check if a file exists or not. Although fs module provides both synchronous and asynchronous methods to achieve this, the synchronous function is more commonly used. This is how you use it:

use strict;
const fs = require(fs);
var readFileAfterChecking = function(){
    if(fs.existsSync(.\myTextFile.txt)){
       var content = fs.readFileSync(.\myTextFile.txt).toString();
       console.log(content);
    }else{
       console.log(File does not exists);
    }
};
readFileAfterChecking();

The fs.existsSync() function returns a boolean value. true if the file exists else false. The fs.existsSync() function can be used to check the existence of file and folders both. Just pass the folder path as the first argument.

Creating a directory
Sometimes there is a need to create some directory from your program either in your server or any command line tool. The fs module provides function to create a directory on your disk. Again both synchronous and asynchronous methods are available.

use strict;
const fs = require(fs);
var createDirectorySync = function(){
    if(!fs.existsSync(.\myDirectory)){
       fs.mkdirSync(.\myDirectory);
    }else{
       console.log(Directory already exists);
    }
};
createDirectorySync();

This fs.mkdirSync() function will crash if the same folder already exists. Hence it is advisable to use it only if the directory does not exists.

Please note that for creating a folder its parent folder should exists. i.e. if you are trying to create /folder1/child1 folder, you need to ensure that folder1 exists. fs.mkdir function will not create the whole path if it does not exists.

Reading Contents of a Directory
fs module provides two functions to read the content of a directory. One of them is synchronous which is frequently used with forEach() function of JavaScript.

Synchronous Method
use strict;
const fs = require(fs);
var readDirectorySync = function(){
    if(fs.existsSync(.\myDirectory)){
       fs.readdirSync(.\myDirectory).forEach(function(content){
           console.log(content);
       });
    }else{
       console.log(Directory does not exists);
    }
};
readDirectorySync();


Asynchronous Method

use strict;
const fs = require(fs);
var readDirectoryAsync = function(){
    if(fs.existsSync(.\myDirectory)){
       fs.readdirSync(.\myDirectory, function(err, contents){
           contents.forEach(function(content){
              console.log(content);
           });
       });
    }else{
       console.log(Directory does not exists);
    }
};
readDirectoryAsync();

The fs.readdirSync() function returns an array containing the name of files and folders which are present in the directory. IT JUST RETURNS THE NAMES. You have to decide if that particular name is of folder or a file. Once we get the array of contents, we iterate over it using forEach() function of JavaScript.

Checking if file or folder
In the previous function we had a problem then fs does not tell us directly which is a directory and which one is a file. For finding out this you need to use another function fs.statSync().

use strict;
const fs = require(fs);
const path = require(path);
var readDirectorySync = function(){
    if(fs.existsSync(.\myDirectory)){
       fs.readdirSync(.\myDirectory).forEach(function(content){
           var stat = fs.statSync(path.join(.\myDirectory, content));
           if(stat.isDirectory()){
               console.log(content + is a directory);
           }else{
               console.log(content + is a file);
           }
       });
    }else{
       console.log(Directory does not exists);
    }
};
readDirectorySync();

The fs.statSync() function returns an object having a function isDirectory(). This returns a boolean true if the passed path is a folder else returns false. The fs.statSync() function requires that you pass the full path of the content you are testing. Else it won’t work.

Deleting a file
The fs module provides a function fs.unlink to delete a FILE (only file) from the disk. Again it has 2 variants synchronous and asynchronous.

use strict;
const fs = require(fs);
var deleteFileAfterChecking = function(){
    if(fs.existsSync(.\myTextFile.txt)){
       fs.unlinkSync(.\myTextFile.txt);
       // File deleted
    }else{
       console.log(File does not exists);
    }
};
deleteFileAfterChecking();

If you try to delete a nonexistent file then the script will crash. So be careful.

Deleting a folder
The fs module has a functions fs.rmdir which accepts path of the directory to be removed as its argument. This function has two variants - a synchronous and another asynchronous.  Note: This command can only delete empty directories. If the directory is not empty then you need to remove it's contents using fs.unlink or fs.rmdir on child directories.


use strict;
const fs = require(fs);
var deleteFolderAfterChecking = function(){
    if(fs.existsSync(.\myFolder)){
       fs.rmdirSync(.\myFolder);
       // Folder deleted
    }else{
       console.log(Folder does not exists);
    }
};
deleteFolderAfterChecking();

That is a lot about file IO in NodeJS.

No comments:
Write comments

Popular Posts