node.js 如何知道nodejs中字节缓冲区内容的实际大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39014861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:30:13  来源:igfitidea点击:

How to know actual size of byte buffer`s content in nodejs?

node.jsbuffer

提问by lor1an

I get files as byte buffers and cannot use fs.stat() method. So I am try to use buf.length but this length refers to the amount of memory allocated for the buffer object and not actually the content size. For example I have file with with size 22,449 bytes. buf.length returns for 39804 for it.

我将文件作为字节缓冲区获取并且不能使用 fs.stat() 方法。所以我尝试使用 buf.length 但这个长度是指为缓冲区对象分配的内存量,而不是实际的内容大小。例如,我有大小为 22,449 字节的文件。buf.length 为它返回 39804。

回答by stdob--

You need byteLength:

你需要byteLength

var buff = fs.readFileSync(__dirname + '/test.txt');
console.log( buff.byteLength );

For node 0.10.21 you can try this:

对于节点 0.10.21 你可以试试这个:

console.log( buff.toString().length );