node.jsbufferbigint

How to read/write a bigint from buffer in node.js 10?


I see that BigInt is supported in node 10. However, there's no ReadBigInt() functionality in the Buffer class.

Is it possible to somehow go around it? Perhaps read 2 ints, cast them to BigInt, shift the upper one and add them to reconstruct the bigint?


Solution

  • With Node v12, functions for reading bigint from buffers was added, so if possible, you should try to use Node v12 or later.

    But these functions are just pure math based on reading integers from the buffer, so you can pretty much copy them into your Node 10-11 code.

    https://github.com/nodejs/node/blob/v12.6.0/lib/internal/buffer.js#L78-L152

    So modifying these methods to not be class methods could look something like this

    function readBigUInt64LE(buffer, offset = 0) {
      const first = buffer[offset];
      const last = buffer[offset + 7];
      if (first === undefined || last === undefined) {
        throw new Error('Out of bounds');
      }
    
      const lo = first +
        buffer[++offset] * 2 ** 8 +
        buffer[++offset] * 2 ** 16 +
        buffer[++offset] * 2 ** 24;
    
      const hi = buffer[++offset] +
        buffer[++offset] * 2 ** 8 +
        buffer[++offset] * 2 ** 16 +
        last * 2 ** 24;
    
      return BigInt(lo) + (BigInt(hi) << 32n);
    }
    

    EDIT: For anyone else having the same issue, I created a package for this.

    https://www.npmjs.com/package/read-bigint