To create a utf-8 buffer from a string in javascript on the web you do this:
var message = JSON.stringify('ping');
var buf = new TextEncoder().encode(message).buffer;
console.log('buf:', buf);
console.log('buf.buffer.byteLength:', buf.byteLength);
This logs:
buf: ArrayBuffer { byteLength: 6 }
buf.buffer.byteLength: 6
However in Node.js if I do this:
var nbuf = Buffer.from(message, 'utf8');
console.log('nbuf:', nbuf);
console.log('nbuf.buffer:', nbuf.buffer);
console.log('nbuf.buffer.byteLength:', nbuf.buffer.byteLength);
it logs this:
nbuf: <Buffer 22 70 69 6e 67 22>
nbuf.buffer: ArrayBuffer { byteLength: 8192 }
nbuf.buffer.byteLength: 8192
The byteLength is way to high. Am I doing something wrong here?
Thanks
byteLength? That seems like an implementation detail, as there's nobyteLengthproperty in the API. What's the value ofnbuf.length?nbuf.lengthproperly gave6, but I thought per stackoverflow.com/a/12101012/1828637 thatBufferis just aUint8Arrayand doingnbuf.buffergives me a javascriptArrayBufferwhich hasbyteLength. Howcome thebyteLengthfof the ArrayBuffer in nbuf is 8192?Bufferinstances are allocated out of larger, underlying buffers - perhaps that's to what the innerbufferproperty refers? - but I'm no expert on the inner workings of Node, so I don't know the definitive answer to that.