讨论问题:如何使用nodejs来计算一个文件的行数?
程序框架如下,我们需要实现countLines
函数
import fs from "fs";
const files = process.argv.slice(2);
function countLines(fileName) {
// You code
}
let total = 0;
for (const fileName of files) {
const num = countLines(fileName);
total += num;
console.log(fileName, num);
}
console.log("total", total);
方法一:
function countLines(fileName) {
const data = fs.readFileSync(fileName, "utf-8");
return data.split(/\r?\n/).length;
}
- 使用同步读文件方法,获取文件的全部数据
- 使用
/\r?\n/
来拆分出所有的行,结果存储在一个矩阵中,该矩阵的长度即为文件的行数。
缺点:需要读取全部的文件,如果文件比较大的话,需要耗费的时间比较多。
还有其他比较好的方法吗?