在“new Buffer(str)”和“Buffer.from(str)”之间选择
Choose between “new Buffer(str)” and “Buffer.from(str)”
根据 the docs, using new Buffer(str)
is deprecated, and people should use Buffer.from(str)
instead. On the other hand, Buffer.from
wasn't available in older versions of node. According to the docs 它是在节点 5.10.0 中添加的。
所以我假设我可以简单地使用像
这样的代码
buf = Buffer.from ? Buffer.from(str) : new Buffer(str);
避免弃用警告,同时保持与旧版本节点的兼容性。事实证明这并没有像预期的那样工作。一些旧版本的节点似乎有一个 from
方法,但是一个不兼容的抛出异常的方法:
TypeError: this is not a typed array.
at Function.from (native)
那么我该如何选择正确的版本呢?我应该以某种方式测试 process.version
吗?或者是否有一些更清洁的解决方案可能更适合其他引擎与节点兼容但不完全相同的可能性?
较新的缓冲区 API 是 backported to v4.x in v4.5.0。您在之前的版本中看到的 Buffer.from()
是 Uint8Array.from()
,这不是一回事。
更好的 API 测试可能是检查 Buffer.allocUnsafe()
.
是否存在
根据 the docs, using new Buffer(str)
is deprecated, and people should use Buffer.from(str)
instead. On the other hand, Buffer.from
wasn't available in older versions of node. According to the docs 它是在节点 5.10.0 中添加的。
所以我假设我可以简单地使用像
这样的代码buf = Buffer.from ? Buffer.from(str) : new Buffer(str);
避免弃用警告,同时保持与旧版本节点的兼容性。事实证明这并没有像预期的那样工作。一些旧版本的节点似乎有一个 from
方法,但是一个不兼容的抛出异常的方法:
TypeError: this is not a typed array.
at Function.from (native)
那么我该如何选择正确的版本呢?我应该以某种方式测试 process.version
吗?或者是否有一些更清洁的解决方案可能更适合其他引擎与节点兼容但不完全相同的可能性?
较新的缓冲区 API 是 backported to v4.x in v4.5.0。您在之前的版本中看到的 Buffer.from()
是 Uint8Array.from()
,这不是一回事。
更好的 API 测试可能是检查 Buffer.allocUnsafe()
.