Reputation: 437
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
Upvotes: 2
Views: 3793
Reputation: 91
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
Upvotes: 4
Reputation: 619
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
Upvotes: 2
Reputation: 705
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);
});
Upvotes: 3