How will you convert a Buffer to JSON in Node.js
Node.js is a platform which is built on chrome’s JavaScript runtime. It is event driven and non blocking I/O module, light weight and an inbuilt server in it. So it is efficient. Buffer class is provided by Node which in turn provides instances for storing integer array like raw data in buffer. Buffer class can be accessed in an application and you don’t need to import buffer module as it is a global class.
Why to use Buffers in Node.js?
Straight binary data cannot be handled by Pure JavaScript although it is Unicode friendly. But it is necessary to read and write binary streams of data to file system while dealing with TCP steams. Node handles these data as octet and it maintains some strategies like storing raw data in Buffer class instances as these instances are designed to handle raw binary data. In node buffer, basically some raw memory is allocated outside V8.S. Buffer instances are commonly used to represent a sequence of encoded characters like UTF-8, UCS2, Base64 ETC. Using some explicit character encoding it is possible to convert data back and forth between Buffer and JavaScript.
Conversion from Buffer to JSON
Buffers and JSON are interchangeable and follows some series of steps to store and read data. There are mainly four steps involved to complete process and they are as follows – · Creating Buffers for data· Writing to Buffers· Reading data from Buffers· Convert Buffers to JSON The fourth step is the most vital one as it is the final output for your operation. Now, the question is -How will you convert a Buffer to JSON in Node.js? The technical syntax to convert from Buffer to JSON is buf.toJSON().This method returns a JSON-representation of the Buffer instance.
Programmatically it can be explained with an example like –
var buff= new Buffer(This is to learn json’);var json = buf.toJSON(buff); console.log(json); Once it is executed it will give a result like below - [ 90, 105, 109, 112, 108, 121, 32, 69, 97, 115, 121, 32, 76, 101, 97, 114, 110, 105, 110, 103 ]
The above representation is identical to JSON array
[vc_row][vc_column][td_block_21 separator=”” tag_slug=”node-js” limit=”40″ tdc_css=””][/vc_column][/vc_row]