Node.js – How to manage files (Read a file)

By | 31/08/2019

In this post, we will see how to read a file using Node.js.

DETERMINING THE EXISTENCE OF A FILE IN A DIRECTORY
[READFILE.JS]

//load module 'fs', used to manage file system
var objectFS = require('fs');
//load module 'path', used to manage the path of files
var path = require('path');
//load module 'readline-sync', use for reading data from console
const readline = require('readline-sync');
//definition of the directory where file to read are
const dirFile = "data";
//reading name of file to find in the directory
let inputFileName = readline.question("Enter the name of the file to verify:  ");
//creation of the complete path
let fileName = path.join(dirFile,inputFileName);

//verify the existence of the file
objectFS.exists(fileName, function(exists) {
    if(exists){
        console.log("The file is in the directory");
    }
    else
    {
        console.log("The file isn't in the directory");
    }
});



If we run the application, this will be the result in case of “file found in the directory”:

Instead, this will be the result in case of “file didn’t find in the directory”:

READING A FILE
[MANAGEREADFILE.JS]

// require fs module
var objFS = require('fs');

function ReadFileCustom(pathFile)
{
    // read file
    objFS.readFile(pathFile, function (err, data) {
        if (err) 
        {
            console.error(err);
        }
        console.log(data.toString());
     });
}


module.exports = {
    ReadFileCustom
}



Now, we will use manageReadFile.js in readfile.js.

[READFILE.JS]

//load fs module
var objectFS = require('fs');
//load module 'path', used to manage the path of files
var path = require('path');
//definition of a constant to use for reading data from console
const readline = require('readline-sync');
//definition of the directory where file to read are
const dirFile = "data";
//reading name of file to find in the directory
let inputFileName = readline.question("Enter the name of the file to verify:  ");
//creation of the complete path
let fileName = path.join(dirFile,inputFileName);

var objManageFile = require('./manageReadFile');

// verify the existance of the file
objectFS.exists(fileName, function(exists) {
    if(exists){
        console.log("The file is in the directory ");
        console.log(" and this is the content:");
        objManageFile.ReadFileCustom(fileName);
    }
    else
    {
        console.log("The file isn't in the directory");
    }
});



If we run the application this will be the output:

READING A FILE LINES BY LINES
[MANAGEFILE.JS]

// require 'fs' module
var objFS = require('fs');
// require 'readline' module for reading single lines in a file
const objLine = require('readline');

function ReadFileCustom(pathFile)
{
    var NumberOfLine = 1;
    const readLineFile = objLine.createInterface({
        input: objFS.createReadStream(pathFile)
    });
    
    // Each line generates an event 
    readLineFile.on('line', (line) => {
        // split the single line in an array
        var varLine = line.split(';');
        console.log(NumberOfLine + "-> Username:" + varLine[0] + " \ ID:" + varLine[1]);
        NumberOfLine++;
    });

    // It is possible to execute a command when the system will finish to read the file
    readLineFile.on('close', () => {
        console.log('File read success');
    });
}



In readfile.js we have to change only the creation of objManageFile:

var objManageFile = require('./manageFile');



Now, if we run the application, this will be the output:



Leave a Reply

Your email address will not be published. Required fields are marked *