buffer to string js code example
Example 1: buffer to string
Single Buffer
If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
});
});
Streamed Buffers
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
});
});
This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.
Example 2: tostring js
var num = 15;
var n = num.toString(); "15"
Example 3: buffer to string
Your code is working. The buffer you have is actually the string "[object Object]".
let b = Buffer.from('[object Object]', 'utf8')
console.log(JSON.stringify(b))
console.log(b.toString('utf8'))
The problem you need to figure out is why is a buffer with that string being sent. It seems like the sender of the buffer needs to call stringify or otherwise serialize the object before sending it. Then you can turn it back to a string with toString() and use JSON.parse() on the string.
Example 4: bytes to string js
const axios = require('axios')
function serializeBytes(sty) {
const string = JSON.stringify({ data: sty })
const input = Array.from(string)
const ouput = input.map((_, i) => string.charCodeAt(i))
return new Uint8Array(ouput)
}
function deserializeBytes(array) {
return new TextDecoder().decode(array)
}
async function httpRequest() {
const resOne = await axios.get('https://jsonplaceholder.typicode.com/photos')
const resTwo = await axios.get('https://jsonplaceholder.typicode.com/photos')
const resThree = await axios.get('https://jsonplaceholder.typicode.com/photos')
const resFour = await axios.get('https://jsonplaceholder.typicode.com/photos')
const resFive = await axios.get('https://jsonplaceholder.typicode.com/photos')
const data = await Promise.all([resOne.data, resTwo.data, resThree.data, resFour.data, resFive.data])
const encoded = serializeBytes(JSON.stringify({ data: data }))
const decoded = deserializeBytes(encoded)
const parse = JSON.parse(decoded)
console.log(parse)
}
httpRequest()