Joschua Xner
Joschua Xner

Reputation: 115

How to download a json object as file?

I am currently trying to let the user of my website download a json object as a json-file. With my following code i get the error message:

Error: Can't set headers after they are sent.
    at SendStream.headersAlreadySent (\node_modules\send\index.js:390:13)
    at SendStream.send (\node_modules\send\index.js:617:10)
    at onstat (\node_modules\send\index.js:729:10)
    at FSReqCallback.oncomplete (fs.js:168:5)
router.post('/about', ensureAuthenticated,
  function (req, res, next) {   
    console.log(req.user);

    var jsonVariable = JSON.stringify(req.user);
    var path_tmp = create_tmp_file(jsonVariable);
    
    res.download(path_tmp);
    
    res.redirect('/about');
    next();
  }
);

Is there a better way to download a json object directly with no need to save it in the filesystem?

Upvotes: 1

Views: 6680

Answers (2)

You can always inject some HTML into a page (or redirect to a page with some client-side JavaScript on it), and download it with the client. Just send the JSON string somehow to the new page you are redirecting to (it can even be a GET parameter), then download it with the following code (assuming the JSON string is in a variable called json):

var a = document.createElement("a")
a.href = URL.createObjectURL(
    new Blob([json], {type:"application/json"})
)
a.download = "myFile.json"
a.click()

Upvotes: 4

Quentin
Quentin

Reputation: 943996

var jsonVariable = JSON.stringify(req.user);
var path_tmp = create_tmp_file(jsonVariable);
res.download(path_tmp);

Send the data with res.json and use content-disposition to make it a download.

res.set('Content-Disposition', 'attachment; filename=example.json')
res.json(req.user);

res.redirect('/about');
next();

And don't do that (which is the cause of the error). You are responding with a download. You can't say "Here is the file you asked for" while, at the same time say, "The file you asked for isn't here, go to this URL instead".

Upvotes: 3

Related Questions