节点fs.readFileSync返回一个uInt8数组而不是原始缓冲区数组? [英] Node fs.readFileSync returns a uInt8 array instead of raw buffer array?

查看:214
本文介绍了节点fs.readFileSync返回一个uInt8数组而不是原始缓冲区数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是为什么:

var myArrayBuffer = fs.readFileSync(file, null)

返回一个uInt8数组而不是一个arrayBuffer吗?为什么这似乎行得通?

returning an uInt8 array instead of a just a arrayBuffer? why does this seem to work?

var myArrayBuffer = fs.readFileSync(file, null).buffer;
var myAArray = new Uint16Array( myArrayBuffer.slice(266,(sizeofArray*sizeOfArrayElement));

为什么fs.readFile会将我的文件解析为uInt8数组?没有任何意义,该文件具有许多不同的数据类型,这些数据类型的长度都不是1个字节.

Why would the fs.readFile parse my file into a uInt8 array? Makes no sense, the file has a bunch of different datatypes that are not 1 byte long.

推荐答案

因为自v3.0.0版以来, Buffer 类继承自 Uint8Array 类.引用文档:

Because since v3.0.0 Buffer class inherits from Uint8Array class. Quoting the doc:

Buffer 实例也是 Uint8Array 实例.但是,与ECMAScript 2015中的 TypedArray 规范存在细微的不兼容.例如,虽然 ArrayBuffer#slice()创建切片的副本,但的实现Buffer#slice()在现有 Buffer 上创建视图而无需复制,从而使 Buffer#slice()效率更高.[...]

Buffer instances are also Uint8Array instances. However, there are subtle incompatibilities with the TypedArray specification in ECMAScript 2015. For example, while ArrayBuffer#slice() creates a copy of the slice, the implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient. [...]

有可能创建一个新的 Buffer ,该缓冲区与通过使用 TypeArray 对象的 .buffer 属性来 TypedArray 实例.

It is possible to create a new Buffer that shares the same allocated memory as a TypedArray instance by using the TypeArray object's .buffer property.

...这正是您的示例中所做的.

... which is exactly what's done in your example.

这篇关于节点fs.readFileSync返回一个uInt8数组而不是原始缓冲区数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆