According to 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 it was added in node 5.10.0.
So I had assumed that I could simply use code like
buf = Buffer.from ? Buffer.from(str) : new Buffer(str);
to avoid deprecation warnings while maintaining compatibility with older versions of node. It turns out this doesn't work as expected. Some older versions of node do seem to have a from
method, but an incompatible one that throws an exception:
TypeError: this is not a typed array.
at Function.from (native)
So how would I go about picking the right version? Should I test process.version
somehow? Or is there some cleaner solution which might be better suited to the possibility of other engines compatible with but not identical to node?
The newer Buffer API was backported to v4.x in v4.5.0. The Buffer.from()
you see in versions prior to that is Uint8Array.from()
, which is not the same thing.
A better API test might be checking the existence of Buffer.allocUnsafe()
.