2

I tried to read line by line in file, but I have a doubt how to print count of line in file using nodejs.

data.js

console.log("123")

console.log("123")


console.log("123")



console.log("123")

file.js

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('./data.js')
});
lineReader.on('line', function (line) {
  console.log('Line from file:', line);
});

I got this ouput

Line from file: console.log("123") Line from file:
Line from file: console.log("123") Line from file:
Line from file: Line from file: console.log("123") Line from file: Line from file: Line from file: Line from file: console.log("123")

but I want how many lines of code in file using node js

SuperStar518
  • 2,814
  • 2
  • 20
  • 35
smith hari
  • 437
  • 1
  • 11
  • 22
  • https://stackoverflow.com/questions/12453057/node-js-count-the-number-of-lines-in-a-file This can help you – abby37 May 14 '19 at 05:35

3 Answers3

4
const fs = require('fs')

fs.readFile('source', 'utf8', (err, data) => {
    console.log(data.split('\n').length)
})

First of all import fs library, then, read file and get length by splitting data

3
var i;
var count = 0;
require('fs').createReadStream(process.argv[2])
  .on('data', function(chunk) {
    for (i=0; i < chunk.length; ++i)
      if (chunk[i] == 10) count++;
  })
  .on('end', function() {
    console.log(count);
  });
Nam V. Do
  • 630
  • 6
  • 27
2
let count = 0;
var lineReader = require('readline').createInterface({
   input: require('fs').createReadStream('./data.js')
});
lineReader.on('data', line => {
   for (i=0; i < line.length; ++i) if (line[i] == 10) count++;
})
.on('end', () => {
   console.log(count);
})

By looping the lines in file you count the number of lines this way. Also you can checkout this link for more details

Thivagar
  • 590
  • 6
  • 13