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';constbuf=Buffer.alloc(10);try{constlen=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';constbuf=Buffer.alloc(10);try{constlen=buf.write('a',-4294967296);console.log(buf.indexOf('a'));}catch(err){console.error(err);}// Prints: 0So should the method check the sign before the converting?
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:node/lib/buffer.js
Line 896 in 6eae414
This may cause some slightly confusing effects:
-offsetis >-buffer.constants.MAX_LENGTH, this produces not so clear error:-offsetis <-buffer.constants.MAX_LENGTH,stringcan be written in an unexpected place:So should the method check the sign before the converting?