Home > Software design >  Converting the Buffer to readable JSON format in Node.js
Converting the Buffer to readable JSON format in Node.js

Time:10-08

I have a buffer text Where I am getting from the SendGrid Inbound Parse webhook.

The Inbound Parse Webhook processes all incoming emails for a domain or subdomain, parses the contents and attachments then POSTs multipart/form-data to a URL that you choose.

The posted content is in buffer format like below

<Buffer 2d 2d 78 64 6b 69 ... >

Now I need to convert this into readable JSON format. When I tried to convert this buffer into JSON, I am getting the result like this.

var json = JSON.parse(buf);

{ type: 'Buffer', data: [ 97, 98, 99 ] }

I need to content like below example. That is the actula format.

enter image description here

When I tried to convert the buffer into string format, I am getting the result what I need. But, that in whole string format. I need it in JSON format. Because I need to some parameters for the responce like "From", "To" information. Is there any way to convert the buffer into readable JSON format.

Buffer -> String -> JSON

Could you please help me in converting the Buffer object to readable JSON object.

CodePudding user response:

You can convert buffer text into JSON format in Node.js using Busboy. Below is an example of how to do it. You can get each field and value.

const Busboy = require("busboy");

exports.hello2 = functions.https.onRequest((req,res)=>{
    
        res.header("Access-Control-Allow-Origin","*");
        res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
    
        const busboy = new Busboy({ headers: req.headers })
        let Data = {}
    
        console.log("Body",req.body);
        console.log("rawBody",req.rawBody);
    
        busboy.on("field", (field, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
            console.log(`FieldName ${field}: ${val}.`)
            Data[field] = val;
        })
    
        busboy.on('finish', () => {
    
            console.log("Data",Data);
    
            console.log("From",Data.from);
            console.log("SPF",Data.SPF);
            console.log("To",Data.to);
            console.log("Subject",Data.subject);
    
            res.status(200).send(Data);
    
        });
    
        busboy.end(req.body)
    
});

CodePudding user response:

You can try this

 const message = Buffer.from(payload, 'base64').toString('utf-8');
 let parsedMessage = JSON.parse(message);
 console.log(parsedMessage);

  • Related