如何知道nodejs中字节缓冲区内容的实际大小?
How to know actual size of byte buffer`s content in nodejs?
我将文件作为字节缓冲区获取,无法使用 fs.stat() 方法。
所以我尝试使用 buf.length 但这个长度指的是为缓冲区对象分配的内存量,而不是实际的内容大小。
例如,我的文件大小为 22,449 字节。
buf.length returns 为 39804 为它。
你需要byteLength
:
var buff = fs.readFileSync(__dirname + '/test.txt');
console.log(Buffer.byteLength(buff));
对于节点 0.10.21 你可以试试这个:
Update buffer.toSTring()
is unsafe, since buffers are meant to store binary data and toString()
will attempt to do character encoding translation which will corrupt the binary data.
console.log(buff.toString().length);
我将文件作为字节缓冲区获取,无法使用 fs.stat() 方法。 所以我尝试使用 buf.length 但这个长度指的是为缓冲区对象分配的内存量,而不是实际的内容大小。 例如,我的文件大小为 22,449 字节。 buf.length returns 为 39804 为它。
你需要byteLength
:
var buff = fs.readFileSync(__dirname + '/test.txt');
console.log(Buffer.byteLength(buff));
对于节点 0.10.21 你可以试试这个:
Update
buffer.toSTring()
is unsafe, since buffers are meant to store binary data andtoString()
will attempt to do character encoding translation which will corrupt the binary data.
console.log(buff.toString().length);