paint-brush
Converting a Buffer to JSON and Utf8 Strings in Nodejsby@amanhimself
217,798 reads
217,798 reads

Converting a Buffer to JSON and Utf8 Strings in Nodejs

by Aman MittalAugust 10th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Nodejs and browser based JavaScript differ because Node has a way to handle binary data even before the ES6 draft came up with <code class="markup--code markup--p-code">ArrayBuffer</code>. In Node, <code class="markup--code markup--p-code">Buffer</code> class is the primary data structure used with most I/O operations. It is a raw binary data that is allocated outside the V8 heap and once allocated, cannot be resized.

People Mentioned

Mention Thumbnail

Company Mentioned

Mention Thumbnail
featured image - Converting a Buffer to JSON and Utf8 Strings in Nodejs
Aman Mittal HackerNoon profile picture

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 is 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:

To create a new buffer instance, in latest and current stable releases of Node:

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.

Convert a Buffer to JSON

Buffers can convert to JSON.

The JSON specifies that the type of object being transformed is a Buffer, and its data.

Convert JSON to Buffer

Convert Buffer to Utf-8 String

.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.

Want to receive more articles like this one? Subscribe me here. Sometimes, I send “never seen before” content to my subscribers.

Find me on Twitter:


Aman Mittal 🖖 (@amanhimself) | Twitter_The latest Tweets from Aman Mittal 🖖 (@amanhimself). #BookBlogger @ https://t.co/UQvyNf1OTC | Developer | #Nodejs |…_twitter.com