Slip 22 - A) Create a Node.js Application to count number of lines in a file and display the count on console.

 Solution:

linecount.js

const readline = require('readline');

const fs = require('fs');
 
var file = 'C:/Users/Public/node_prog/searchf.txt';

var linesCount = 0;

var rl = readline.createInterface({

    input: fs.createReadStream(file),

    output: process.stdout,

    terminal: false

});

rl.on('line', function (line) {

    linesCount++; // on each linebreak, add +1 to 'linesCount'

});

rl.on('close', function () {

    console.log(linesCount); // print the result when the 'close' event is called

});

 

Install readline module

C:\Users\Your Name>npm readline

Then initiate

C:\Users\Your Name>node linecount.js

 

Post a Comment

0 Comments