function calcLineCount(filename, callback) { var fs = require('fs'); var fileStream = fs.createReadStream(filename), lines = 0; fileStream.on('data', function (buf) { lines += buf.toString().match(/\n/g).length + 1; }); fileStream.on('end', function () { callback(lines); });}calcLineCount('/Users/piaoger/Downloads/lc.js', function(lines) { console.log(lines);});
其实也可以直接在Node.js中调用“wc”来解决问题的。只不过我之前用str.split(/\n/).length来做,应该会比match慢吧。
Piaoger