.indexOf returns 0 for a Buffer

  • const buf = Buffer.alloc(5);
    buf[0] = 1;
    buf[1] = 2;
    buf[2] = 3;
    buf[3] = 0;
    buf[4] = 5;
    console.log("End test...")

    I expect this to return a 3 but it returns a 0. Output from NodeJS and lowjs below.



  • This is a deviation in behaviour between Node.JS and Duktape, who implements the Buffer.

    However, I think it is weird that Buffer.indexOf(Number) is actually supported at all in Node.JS. For me, buf.indexOf(0) is not a good way to write it anyways. What is 0? A 8 bit value? It could just as well be interpreted as a float.

    Thus, I would write it more explicitly anyways:

    const buf2 = Buffer.alloc(1);

    This also returns a 3, here we have the same behaviour.

    So if you want this fixed, add it as a GitHub issue to DukTape, but I am not really enthusiastic about this 🙂

  • I am currently using your suggestion as a workaround. Thing is, if you look at the official Node JS documentation it says a number passed to the function is interpreted as a unsigned 8 bit integer from 0 to 255. JS being such a free for all and untyped allows for such things. Also, considering a buffer is just an array of bytes, defaulting a number to a value from 0 to 255 does align with the JS notion of making things really simple to the point of realizing you are standing on a landmine when it is too late.

    I am getting a buffer from an i2c device and the first occurrence of a 0 in the buffer indicates the end of the data and since the data can be variable length, there is a need to find the first 0.


  • Sorry, I did not mean to say that it is not documented. I just wanted to say that people could misinterpret the code. Not everybody has the documentation of Node in their head.

    I also completly understand the untyped nature of JavaScript. But that should not be extended to Buffers, if you ask me. As a good programming practice, when using a Buffer, I would always explicitly write the encoding (8, 16, 32, float, double, LE, BE). So, for me my suggestion is not a workaround at all 🙂

    All in all, good, problem solved.

Log in to reply