最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to check how many lines of code in file using node js - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited May 14, 2019 at 5:53 SuperStar518 2,9052 gold badges21 silver badges37 bronze badges asked May 14, 2019 at 5:32 smith harismith hari 4371 gold badge11 silver badges23 bronze badges 1
  • stackoverflow./questions/12453057/… This can help you – abby37 Commented May 14, 2019 at 5:35
Add a ment  | 

3 Answers 3

Reset to default 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

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);
  });
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

发布评论

评论列表(0)

  1. 暂无评论