Nodejs and browser based JavaScript differ because Node has a way to handle binary data even before the ES6 draft came up with ArrayBuffer
. In Node, Buffer
class is the primary data structure used with most I/O operations. It's a raw binary data that is allocated outside the V8 heap and once allocated, cannot be resized.
Before Nodejs v6.0, to create a new buffer you could just call the constructor function with new
keyword:
https://gist.github.com/ea236e5343fc0e4a5295071d27fa48d3
To create a new buffer instance, in latest and current stable releases of Node:
https://gist.github.com/909e075f2066c5826d0e60de85fbe831
The new Buffer()
constructor have been deprecated and replaced by separate Buffer.from()
, Buffer.alloc()
, and Buffer.allocUnsafe()
methods.
More information can be read through official documentation.
Buffers can convert to JSON.
https://gist.github.com/15a3d9b83a95ef426b05ddca19dbb374
The JSON specifies that the type of object being transformed is a Buffer
, and its data.
https://gist.github.com/1c42f6674af95b8d347338b7546669d1
https://gist.github.com/ed7997521d3147c252194c0ba4074a0b
.toString()
is not the only way to convert a buffer to a string. Also, it by defaults converts to a utf-8 format string.
The other way to convert a buffer to a string is using StringDecoder
core module from Nodejs API.