buffer: buf.write(string, offset) with negative offset · Issue #27043 · nodejs/node (original) (raw)
All other Node.js Buffer methods either support negative offsets or throw errors for all negative integers stating that offset must be >= 0.
However, buf.write(string, offset) does not check if an offset is negative, but just converts it to uint32:
This may cause some slightly confusing effects:
- If
-offset
is >-buffer.constants.MAX_LENGTH
, this produces not so clear error:
'use strict';
const buf = Buffer.alloc(10);
try { const len = buf.write('a', -1); console.log(buf.indexOf('a')); } catch (err) { console.error(err.toString()); }
// Prints: RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
- If
-offset
is <-buffer.constants.MAX_LENGTH
,string
can be written in an unexpected place:
'use strict';
const buf = Buffer.alloc(10);
try { const len = buf.write('a', -4294967296); console.log(buf.indexOf('a')); } catch (err) { console.error(err); }
// Prints: 0
So should the method check the sign before the converting?