使用 node.js 和 node-csv-parser(节点模块)提示下载 csv 文件作为弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13070194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:32:30  来源:igfitidea点击:

Prompt a csv file to download as pop up using node.js and node-csv-parser (node module)

node.jscsvexportexport-to-csv

提问by Manish Kumar

Recently I have started working with node.js. While going through a requirement in one of my projects I am facing an issue where I should be able to write some data to a csv file dynamically and let it prompt as a popup to download for user (with save and cancel options - as we normally see). After googling for some time I decided to use csv npm module https://github.com/wdavidw/node-csv-parser. I am able to write data into a file and save it using this module. I want to prompt a popup for saving this file with/without saving the file.

最近我开始使用 node.js。在我的一个项目中完成一项要求时,我遇到了一个问题,我应该能够将一些数据动态写入 csv 文件,并让它作为弹出窗口提示用户下载(具有保存和取消选项 - 就像我们通常看)。谷歌搜索一段时间后,我决定使用 csv npm 模块https://github.com/wdavidw/node-csv-parser。我能够将数据写入文件并使用此模块保存它。我想在保存/不保存文件的情况下提示保存此文件的弹出窗口。

my code looks something like this:

我的代码看起来像这样:

    // Sample Data 
    var data = [["id", "subject1", "subject2", "subject3"], ["Hyman", 85, 90, 68], ["sam", 77, 89, 69]]

    // Server Side Code    
    var csv = require('../../node_modules/csv');            
    var fs = require('fs');

    createCSV = function(data, callback) {
        csv().from(data).to(fs.createWriteStream('D:/test.csv')) // writing to a file           
    }

    // Client side call sample
    $("#exportToCSV").click(function() {
        callToServer.createCSV(data);
       return false;
    });

This is working good as far as writing the csv file is concerned.

就编写 csv 文件而言,这很有效。

  • I want to prompt this file immediately to download for users.
  • If this can be done without saving the file, that will be great.
  • How can I set content-type and content-disposition as we do in PHP
  • 我想立即提示此文件供用户下载。
  • 如果这可以在不保存文件的情况下完成,那就太好了。
  • 如何像在 PHP 中那样设置内容类型和内容处置

Any help is greatly appreciated. -Thanks

任何帮助是极大的赞赏。-谢谢

回答by joel.bowen

Manish Kumar's answer is spot on - just wanted to include a Express 4syntax variant to accomplish this:

Manish Kumar 的回答恰到好处 - 只是想包含一个Express 4语法变体来实现这一点:

function(req, res) {
  var csv = GET_CSV_DATA // Not including for example.

  res.setHeader('Content-disposition', 'attachment; filename=testing.csv');
  res.set('Content-Type', 'text/csv');
  res.status(200).send(csv);

}

回答by Manish Kumar

I did it something like this :

我做了这样的事情:

http.createServer(function(request, response) {
    response.setHeader('Content-disposition', 'attachment; filename=testing.csv');
    response.writeHead(200, {
        'Content-Type': 'text/csv'
    });

    csv().from(data).to(response)

})
.listen(3000);

回答by Palani

Following solution is for Express

以下解决方案适用于 Express

Express is evolved, instead of setting attachment and content type header, directly use attachment api http://expressjs.com/4x/api.html#res.attachment

Express是进化而来的,不用设置附件和内容类型header,直接使用附件api http://expressjs.com/4x/api.html#res.attachment

Note: attachment() don't transfer the file, it just sets filename in header.

注意:attachment() 不传输文件,它只是在标题中设置文件名。

response.attachment('testing.csv');
csv().from(data).to(response);

回答by Federico

Express-csv is a great module for writing csv contents to stream from a node.js server, which will be sent as a response to the client (and downloaded as a file). Very easy to use.

Express-csv 是一个很棒的模块,用于将 csv 内容从 node.js 服务器写入流,它将作为响应发送到客户端(并作为文件下载)。非常容易使用。

app.get('/', function(req, res) {
  res.csv([
    ["a", "b", "c"]
  , ["d", "e", "f"]
  ]);
});

The docs: https://www.npmjs.com/package/express-csv

文档:https: //www.npmjs.com/package/express-csv

When you pass an object, you need to prepend the headers explicitly (if you want them). Here's my my example using npm mysql

当您传递一个对象时,您需要显式地预先添加标头(如果需要的话)。这是我使用npm mysql 的示例

router.route('/api/report')
    .get(function(req, res) {
            query = connection.query('select * from table where table_id=1;', function(err, rows, fields) {
                if (err) {
                    res.send(err);
                }
                var headers = {};
                for (key in rows[0]) {
                    headers[key] = key;
                }
                rows.unshift(headers);
                res.csv(rows);
            });
    });

回答by Max

Check out this answer: Nodejs send file in response

看看这个答案:Nodejs send file in response

Basically, you don't have to save the file to the hard drive. Instead, try sending it directly to the response. If you're using something like Express then it would look something like this:

基本上,您不必将文件保存到硬盘驱动器。相反,尝试将其直接发送到response. 如果您使用的是 Express 之类的东西,那么它看起来像这样:

var csv = require('csv');
req.get('/getCsv', function (req, res) {
    csv().from(req.body).to(res);
});