Ankur Chavda
Ankur Chavda

Reputation: 173

Convert buffered file data to Json object: express-fileupload

I am sending a JSON file over http. The file is available on req.files using the express-fileupload middleware. I am getting the file as a buffered data. I want to convert the file to a JSON object.

app.post('/start', function(req, res){
    if(!req.files.seed)
        res.status(400).send("Please upload the seed file");

    var file = req.files.seed;
    var obj = //Convert the file to JSON object and send it to create instance;
    instance.createInstance(obj);
    res.status(200).send("Started....");    
});

When printed, the file looks like something this

{ name: 'seed.json',
  data: <Buffer 7b 0d 0a 09 22 61 72 72 61 79 22 3a 20 5b 20 31 2c 20 31 20 5d 2              c 0d 0a 09 22 72 65 63 75 72 72 65 6e 63 65 22 3a 20 7b 0d 0a 09 09 22 73 65 63               6f 6e ... >,
  encoding: '7bit',
  mimetype: 'application/json',
  mv: [Function: mv] }

I tried using JSON.parse(file) but SyntaxError: Unexpected token o in JSON at position 1 pops up.

I also tried using converting it to a string using

var text = file.toString(file,'utf8')
var obj = JSON.parse(text)

but this also doesn't seem to work. The properties of this objects, when accessed are undefined.

The JSON file structure.

{
    "array": [ 1, 1 ],
    "recurrence": {
        "second": 50,
        "minute": null,
        "hour": null,
        "dayOfweek": null
    },
    "campaign": {
        "sender": "StartUp India Yatra",
        "email": "[email protected]",
        "subject": "{Invitation} StartUp India Yatra Chapter",
        "title": "StartUp India Yatra Campaign"
    },
    "condition": {
        "open": {
            "greaterThanEqual": 1,
            "lessThan": 2
        },
        "campaignSummary": null
    },
    "textPath": "../template.txt",
    "htmlPath": "../template.html",
    "path": "../emailer/index.js"
    "retailerId": "4"
}

Upvotes: 2

Views: 2731

Answers (1)

Alexandru Olaru
Alexandru Olaru

Reputation: 7112

Given what you presented in the debug, your encoding is not utf8 but 7bit. So for a proper decoding you will need to change a bit your code.

var file = req.files.seed;
var obj = JSON.parse(file.data.toString('ascii'));

// ... do your creation logic

Any way you can play with the utf8, ascii econdings to see if you do not have JSON.parse problems.

Upvotes: 3

Related Questions