Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose between “new Buffer(str)” and “Buffer.from(str)”

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?

like image 210
MvG Avatar asked Sep 09 '26 13:09

MvG


1 Answers

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().

like image 73
mscdex Avatar answered Sep 12 '26 03:09

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!