Skip to content

Commit

Permalink
fix: avoid using deprecated Buffer constructor (#94)
Browse files Browse the repository at this point in the history
* fix: avoid using deprecated Buffer constructor

Buffer.alloc() is supported on Node.js >= 4.5.0, and allocates a zero-filled
buffer on all supported versions.

This solves two issues:
 * Buffer() constructor (aka 'new Buffer()') is deprecated, so avoid using it
 * On 4.x and 6.x, Buffer(number) is not zero-filled, so this code was
   allocating an uninitialized Buffer when file length was less than 150, so
   the behaviour of readShebang() was actually undefined in that case (as in
   could have returned anything, depending on the uninitialized memory chunk).

Refs: https://nodejs.org/api/deprecations.html#deprecations_dep0005_buffer_constructor

* readShebang: name reused inline constant

'150' was used two times, it deserves a name.
It's the size of the pre-read buffer.

* readShebang: Buffer API compat for old Node.js

To be reverted when dropping outdated Node.js versions support.
  • Loading branch information
ChALkeR authored and satazor committed Mar 2, 2018
1 parent 6b64987 commit d5770df
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/util/readShebang.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,23 @@ const shebangCommand = require('shebang-command');

function readShebang(command) {
// Read the first 150 bytes from the file
const size = 150;

let buffer;
if (Buffer.alloc) {
// Node.js v4.5+ / v5.10+
buffer = Buffer.alloc(size);
} else {
// Old Node.js API
buffer = new Buffer(size);
buffer.fill(0); // zero-fill
}

let fd;
const buffer = new Buffer(150);

try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, 150, 0);
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) { /* Empty */ }

Expand Down

0 comments on commit d5770df

Please sign in to comment.