Home > database >  How to convert NodeJS form-data object into JSON string
How to convert NodeJS form-data object into JSON string

Time:09-28

I am using form-data package in my NodeJS application to send formdata. I am using Axios interceptor for logging the requests in a file. In axiosIns.config.data, I need the JSON string corresponding to the formdata set but currently it's FormData Object.

This library provides a toString method but on using that I have found that it returns a static string [object FormData] instead of the stringified input. I have opened an issue regarding that but seems unattended.

I have created a repl for regenerating that.

Is there any way so that I can convert my formdata object into a readable, loggable, preferably JSO string?

CodePudding user response:

I solved It

const FormData =  require("form-data");

var data = new FormData();
data.append("modid", "IM");
data.append("token", "provider\nagg");
data.append("cat_type", "3");

var boundary = data.getBoundary();

var data_row = data.getBuffer().toString();

console.log(rawFormDataToJSON(data_row,boundary));

function rawFormDataToJSON(raw_data,boundary){
    var spl = data_row.split(boundary);
    var data_out = [];
    spl.forEach(element => {
        let obj = {};
        let ll = element.split("\n");
         if(ll[1]){
            let key = ll[1].split("=")[1].replace('"',"").replace('"\r',"");
            let val = "";
            if(ll.length > 3){
                for (let i = 3; i < ll.length; i  ) {
                    val  = ll[i] "\n";
                }
            }
            obj[key] = val.replace("--","").replace("\r\n\n","");
            data_out.push(obj);
         }
    });
    return data_out;
}

Expected Output

[ { modid: 'IM' }, { token: 'provider\nagg' }, { cat_type: '3' } ]

CodePudding user response:

Edit: I got reply on the github issue mentioned and as per that "this package doesn't intend to implement the toString() in a way to return stringified data. If I want spec-compliant FormData, I'll need to install the other packages mentioned. So it's not an issue but an intended unimplemented feature."


I tried below code, seems fine but not recommended as it's based on text splitting and filtering, if text format changes, it might create issue. This is the sandbox for the same.

const FormData = require("form-data");

var data = new FormData();
data.append("modid", "IM");
data.append("token", "provider");
data.append("cat_type", "3");

const objectifyFormdata = (data) => {
    return data
        .getBuffer()
        .toString()
        .split(data.getBoundary())
        .filter((e) => e.includes("form-data"))
        .map((e) =>
            e
                .replace(/[\-] $/g, "")
                .replace(/^[\-] /g, "")
                .match(/\; name\=\"([^\"] )\"(.*)/s)
                .filter((v, i) => i == 1 || i == 2)
                .map((e) => e.trim())
        )
        .reduce((acc, cur) => {
            acc[cur[0]] = cur[1];
            return acc;
        }, {});
};

console.log(objectifyFormdata(data));
// { modid: 'IM', token: 'provider', cat_type: '3' }

  • Related