Skip to content

Commit

Permalink
Merge pull request #506 from ChALkeR/patch-1
Browse files Browse the repository at this point in the history
Fix deprecated Buffer constructor usage and add safeguards
  • Loading branch information
Stuk committed Feb 21, 2019
2 parents 56574c3 + 8461371 commit 05d8520
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions lib/nodejsUtils.js
Expand Up @@ -14,13 +14,16 @@ module.exports = {
* @return {Buffer} a new Buffer.
*/
newBufferFrom: function(data, encoding) {
// XXX We can't use `Buffer.from` which comes from `Uint8Array.from`
// in nodejs v4 (< v.4.5). It's not the expected implementation (and
// has a different signature).
// see https://github.com/nodejs/node/issues/8053
// A condition on nodejs' version won't solve the issue as we don't
// control the Buffer polyfills that may or may not be used.
return new Buffer(data, encoding);
if (Buffer.from && Buffer.from !== Uint8Array.from) {
return Buffer.from(data, encoding);
} else {
if (typeof data === "number") {
// Safeguard for old Node.js versions. On newer versions,
// Buffer.from(number) / Buffer(number, encoding) already throw.
throw new Error("The \"data\" argument must not be a number");
}
return new Buffer(data, encoding);
}
},
/**
* Create a new nodejs Buffer with the specified size.
Expand All @@ -31,7 +34,9 @@ module.exports = {
if (Buffer.alloc) {
return Buffer.alloc(size);
} else {
return new Buffer(size);
var buf = new Buffer(size);
buf.fill(0);
return buf;
}
},
/**
Expand Down

0 comments on commit 05d8520

Please sign in to comment.