快速发送Json文件 [英] Sending a Json File in express

查看:57
本文介绍了快速发送Json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在应用程序中设置路由,以在打开.json文件时下载该文件,但是我不太清楚res.sendFile的工作方式.当我发送文件时,由于某种原因,客户端会收到一个名称正确的完全空白的文件.

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.

这是我的代码:

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?

推荐答案

您正在使用 fs.writeFile 函数,但不等待回调(这将指示错误或成功),请参见: https://nodejs.org/api/fs.html#fs_fs_writefile_filename_data_options_callback .

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.

要解决此问题,请将所有内容从 res.setHeader 放到函数的末尾,并将其添加为 fs.writeFile 的最后一个参数.

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

这篇关于快速发送Json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆