简体   繁体   English

具有Express的Node.js-返回到.CSV文件的链接,而不是下载它

[英]Node.js with Express - returning a link to a .CSV file instead of downloading it

I am creating an application that turns json from a database into a csv file and serves it to the user based on selected parameters. 我正在创建一个应用程序,将json从数据库转换为csv文件,并根据所选参数将其提供给用户。 Consider the following portion of a router my node server that returns converted CSV data: 考虑节点服务器路由器的以下部分,该部分返回转换后的CSV数据:

request(options, function (err, body) {
    if (err) {
        return res.status(400).json({ success: false, data: err});
    }
    else {
        var jsonresponse = JSON.parse(body);
        if (jsonresponse.timed_out) {
            return res.status(504).json({ success: true, data: "timed out"});
        }
        else {
            jsonexport(jsonresponse, function(err, data){
                if(err) return console.log(err);
                return res.status(200).send(data);
            });
        }
    }
}

Currently, the above code takes a json response and converts it into csv using jsonexport , then serves the raw csv data to the client. 当前,以上代码采用json响应,并使用jsonexport将其转换为csv,然后将原始csv数据提供给客户端。

I know I can use the file-system module to download the data as a file to local storage before the API call finishes, but is there a way I can create the .csv file and store it somewhere for the client to later access? 我知道我可以在API调用完成之前使用文件系统模块将数据作为文件下载到本地存储中,但是有没有办法我可以创建.csv文件并将其存储在客户端以供以后访问? I want to complete more logic after the API call is finished on the client side before letting the user have the file. 在让用户拥有文件之前,我想在客户端完成API调用后完成更多逻辑。

Thank you in advance for your help! 预先感谢您的帮助!

You can use the express.static() function to accomplish your goal. 您可以使用express.static()函数来实现您的目标。 ( docs ) docs

Consider the following example: 考虑以下示例:

var express = require('express')
var app = express();

app.use('/files', express.static('/files');

This will make it so the /files endpoint serves everything inside the /files folder statically. 这样就可以使/files端点静态地提供/files夹中的所有内容。 Meaning if you have, say, a file called test.csv stored in that folder, you could access it through http://yourhost:port/files/test.csv . 这意味着,如果您在该文件夹中存储了一个名为test.csv文件,则可以通过http://yourhost:port/files/test.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM