如何在node.js中获取string的字节?

我想读取文件的字节大小。 我有这个

var path = 'training_data/dat1.txt'; var fs = require("fs"); //Load the filesystem module var stats = fs.statSync(path); var fileSizeInBytes = stats["size"]; var accSize = 0; var lineReader = require('readline').createInterface({ input: fs.createReadStream(path) }); lineReader.on('line', function (line) { accSize += Buffer.byteLength(line, 'utf8'); console.log(accSize + "/" + fileSizeInBytes); }); lineReader.on('close', function() { console.log('completed!'); }); 

但它不打印出正确的文件大小。

 7/166 16/166 23/166 32/166 39/166 48/166 55/166 64/166 71/166 80/166 87/166 96/166 103/166 112/166 

它打印这个例子。

有谁知道什么是错的?

lineReader不包含缓冲区中的换行符\n字符,因为每行都被读取,这是您的字节丢失的地方。

尝试这个:

 accSize += Buffer.byteLength(line + '\n', 'utf8'); 

编辑

如果正在读取的文件使用Windows行结束符,则需要添加两个字符,因为除了换行之外,还会有一个回车符,用'\r\n' 。 ( 更多细节见这里 )