John Kulp
John Kulp

Reputation: 123

Sending a Json File in express

I'm trying to set route in my application to download a .json file when it is opened, however I can't quite figure out how res.sendFile works. When I send my file, for some reason the client receives a completely blank file with the correct name.

Here's my code:

fs.writeFile(path.join(__dirname, '../../public/send/file.json'), JSON.stringify(resultDict));

res.setHeader('Content-disposition', 'attachment; filename=file.json');

var options = {
    root: __dirname + '/../../public/send/',
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
};

res.sendFile('file.json', options, function(err){
    if(err){
        console.log(err);
        res.status(err.status).end();
    }
    else{
        console.log('Sent: ' + "file.json");
    }
});

Why is the sent file completely empty?

Upvotes: 0

Views: 3165

Answers (1)

major-mann
major-mann

Reputation: 2652

You are using the fs.writeFile function, but not waiting for the callback (which will indicate error, or success) See: https://nodejs.org/api/fs.html#fs_fs_writefile_filename_data_options_callback.

Because of this, by the time the send file code runs, the file has not been written, and so blank contents are sent.

To fix this put everything from res.setHeader to the end in a function and add it as the last argument to fs.writeFile.

Upvotes: 1

Related Questions