Skip to content

Commit d5770df

Browse files
ChALkeRsatazor
authored andcommitted
fix: avoid using deprecated Buffer constructor (#94)
* 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.
1 parent 6b64987 commit d5770df

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

lib/util/readShebang.js

+13-2
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,23 @@ const shebangCommand = require('shebang-command');
55

66
function readShebang(command) {
77
// Read the first 150 bytes from the file
8+
const size = 150;
9+
10+
let buffer;
11+
if (Buffer.alloc) {
12+
// Node.js v4.5+ / v5.10+
13+
buffer = Buffer.alloc(size);
14+
} else {
15+
// Old Node.js API
16+
buffer = new Buffer(size);
17+
buffer.fill(0); // zero-fill
18+
}
19+
820
let fd;
9-
const buffer = new Buffer(150);
1021

1122
try {
1223
fd = fs.openSync(command, 'r');
13-
fs.readSync(fd, buffer, 0, 150, 0);
24+
fs.readSync(fd, buffer, 0, size, 0);
1425
fs.closeSync(fd);
1526
} catch (e) { /* Empty */ }
1627

0 commit comments

Comments
 (0)