Converting a Buffer to JSON and Utf8 Strings in Nodejs

Published on Aug 10, 2017

2 min read

NODEJS

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:

1let newBuff = new Buffer('New String');

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

1let newBuff = Buffer.from('New String');

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.

1let bufferOne = Buffer.from('This is a buffer example.');
2console.log(bufferOne);
3
4// Output: <Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66
5// 66 65 72 20 65 78 61 6d 70 6c 65 2e>
6
7let json = JSON.stringify(bufferOne);
8console.log(json);
9
10// Output: {"type":"Buffer","data":[84,104,105,115,32,105,
11// 115,32,97,32,98,117,102,102,101,114,32,101,120,97,109,
12// 112,108,101,46]}

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

Convert JSON to Buffer

🔗
1let bufferOriginal = Buffer.from(JSON.parse(json).data);
2console.log(bufferOriginal);
3
4// Output: <Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66
5// 66 65 72 20 65 78 61 6d 70 6c 65 2e>

Convert Buffer to Utf-8 String

🔗
1console.log(bufferOriginal.toString('utf8'));
2
3// Output: This is a buffer example.

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


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. In this blog, I write about Technical writing, Node.js, React Native and Expo.

Currently, working at Expo. Previously, I've worked as a Developer Advocate, and Senior Content Developer with companies like Draftbit, Vercel and Crowdbotics.


Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.