Node.js – Convert JSON to Buffer
Node.js – To convert JSON to Buffer, first convert JSON object to string JSON.stringify(jsonObj); , then use Buffer.from(jsonStr) method to read the JSON string to a buffer.
Example
Following is an example that demonstrates how to convert a JSON Object to a Buffer :
const msg = '{"name":"John", "age":"22"}'; var jsonObj = JSON.parse(msg); // convert JSON object to String var jsonStr = JSON.stringify(jsonObj); // read json string to Buffer const buf = Buffer.from(jsonStr); console.log(buf.length); |
$ node convert-json-to-buffer.js 26 |
In our next Node.js Tutorial, we shall learn to convert Buffer data to a JSON object.