[英]how to check 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
. 我试图逐行读取文件中的内容,但是我
nodejs
如何使用nodejs
打印文件中的行数。
data.js data.js
console.log("123")
console.log("123")
console.log("123")
console.log("123")
file.js 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:
来自文件的行:console.log(“ 123”)来自文件的行:
Line from file: console.log("123") Line from file:来自文件的行:console.log(“ 123”)来自文件的行:
Line from file: Line from file: console.log("123") Line from file: Line from file: Line from file: Line from file: console.log("123")来自文件的行:来自文件的行:console.log(“ 123”)来自文件的行:来自文件的行:来自文件的行:来自文件的行:console.log(“ 123”)
but I want how many lines of code in file using node js 但是我想要使用节点js文件中多少行代码
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
您也可以查看此链接以获取更多详细信息
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 首先导入fs库,然后读取文件并通过拆分数据来获取长度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.