From dd608591a891aaecf3aa5ba44f87768f0c254f73 Mon Sep 17 00:00:00 2001 From: "dcposch@dcpos.ch" Date: Wed, 7 Dec 2016 00:36:16 -0800 Subject: [PATCH] doc: clarify Buffer.indexOf/lastIndexOf edge cases PR-URL: https://github.com/nodejs/node/pull/10162 Fixes: https://github.com/nodejs/node/issues/9801 Reviewed-By: Roman Reiss Reviewed-By: Stephen Belanger Reviewed-By: Trevor Norris Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Rich Trott --- doc/api/buffer.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index adc9d6b104680b..c9f15b14476083 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1151,6 +1151,30 @@ console.log(utf16Buffer.indexOf('\u03a3', 0, 'ucs2')); console.log(utf16Buffer.indexOf('\u03a3', -4, 'ucs2')); ``` +If `value` is not a string, number, or `Buffer`, this method will throw a +`TypeError`. If `value` is a number, it will be coerced to a valid byte value, +an integer between 0 and 255. + +If `byteOffset` is not a number, it will be coerced to a number. Any arguments +that coerce to `NaN` or 0, like `{}`, `[]`, `null` or `undefined`, will search +the whole buffer. This behavior matches [`String#indexOf()`]. + +```js +const b = Buffer.from('abcdef'); + +// Passing a value that's a number, but not a valid byte +// Prints: 2, equivalent to searching for 99 or 'c' +console.log(b.indexOf(99.9)); +console.log(b.indexOf(256 + 99)); + +// Passing a byteOffset that coerces to NaN or 0 +// Prints: 1, searching the whole buffer +console.log(b.indexOf('b', undefined)); +console.log(b.indexOf('b', {})); +console.log(b.indexOf('b', null)); +console.log(b.indexOf('b', [])); +``` + ### buf.includes(value[, byteOffset][, encoding])