【问题标题】:Node - CSV is not working节点 - CSV 不工作
【发布时间】:2014-06-01 05:16:48
【问题描述】:

我正在使用 nodejs v0.10.26 和 expressjs。
我想在应用程序中实现 CSV 格式的数据导出功能,为此我使用 node-csv 0.3.7
JS

var csv = require('csv');
res.setHeader('Content-disposition', 'attachment; filename=Report.csv');
res.writeHead(200, {'Content-Type': 'text/csv'});
csv().from(callBack).to(res);

但它没有提示任何 CSV 文件,我只在服务响应中获取文本数据。
谁能告诉我我的代码有什么问题?在这种情况下我想要 CSV 文件提示符。

更新

这里 callBack = JSON 对象,其中包含数据
res = 响应

【问题讨论】:

  • 什么是callBackres 是什么?在这里工作不多。
  • @AaronDufour:这里 callBack = JSON 对象,其中包含数据和 res = 响应

标签: node.js express export-to-csv


【解决方案1】:

试试这个:

var csv = require('csv');
res.setHeader('Content-disposition', 'attachment; filename=Report.csv');
res.writeHead(200, {'Content-Type': 'text/csv'});

csv.parse(callBack, function(err, output) {
    if(err){
        throw err;
    }

    res.write(output);
});

我用这段代码测试了csv.parse 函数:

var parse = require('csv-parse');

var data = '"1","2","3","4"\n"a","b","c","d"';


parse(data, function(err, output) {
        if(err){
                throw err;
        }

        console.log(output);
});

另外,作为旁注,我建议不要调用包含数据的变量callBack,因为惯例倾向于将回调函数命名为callback。它会按照你的方式工作,但它会让任何阅读你的代码的人感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2018-10-18
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多