node.js - Nodejs 发送部分响应

标签 node.js csv export-to-csv

mongodb 集合中有 20,000 条记录。我正在将所有这些记录导出到一个 csv 文件中。我使用这个发送部分响应:

res.writeHead(200, {
                     "Content-Type": "application/csv",
                     "Content-disposition": "attachment; filename='import.csv'"
 });

res.write(data + '0', "binary");

以上代码以 500 条为一批执行。当所有记录都处理完后,我将结束使用此代码。

if (++responseCount == loopCount) {
  res.end();
}

但是我得到了这个错误:

Can't set headers after they are sent.

但是我下载了包含 500 条记录的文件。

这是我的完整代码。

var exportData = function (req, res, next) {

var limit = 500;
var responseCount = 0;
var loopCount = 1;
var size = 30000;

//Get 500 records at one time
var getData = function (req, start, cb) {
    req.db.collection('items').find().skip(start).limit(limit).toArray(function (err, records) {
        if (err) throw err;
        cb(null, records);
    });
};

if (size > limit) {
    loopCount = parseInt(req.size / limit);

    if ((req.size % limit) != 0) {
        loopCount += 1;
    }
}

for (var j = 0; j < loopCount; j++) {

    getData(req, limit * j, function (err, records) {

        if (err) throw err;

        records.forEach(function (record) {
            //Process record one by one
        });

        res.write(records);

        if (++responseCount == loopCount) {
            res.setHeader('Content-type', 'application/csv');
            res.setHeader("Content-disposition", 'attachment; filename="import.csv"');
            res.end();

        }

    });
}
};

最佳答案

为什么不直接流式传输数据?你可以使用 Mongoose query.stream特征。文档中的示例:

// follows the nodejs 0.8 stream api
Thing.find({ name: /^hello/ }).stream().pipe(res)

流将为您处理数据流。作为 node.js 流,您还可以监听事件:

// manual streaming
var stream = Thing.find({ name: /^hello/ }).stream();

stream.on('data', function (doc) {
  // do something with the mongoose document
}).on('error', function (err) {
  // handle the error
}).on('close', function () {
  // the stream is closed
});

关于node.js - Nodejs 发送部分响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31339652/

相关文章:

node.js - Remix.run 不使用 node.js 作为后端吗?

postgresql - 如何将 PostgreSQL 数据库中的所有表导出到 csv 文件?

node.js - 无法在本地安装 gulp。当我在 cmd 中运行 "npm install gulp --save-dev"命令时失败

node.js - MongoDB 更新 $pull 多个数组中的文档

vba - 使用vba覆盖csv文件

excel - 如何在 Excel 2010 中使用 VBA 查询 UTF-8 编码的 CSV 文件?

r - 在 read.table() : incomplete final line found by readTableHeader

php - 是否有可能使用 PHP 获取 Google 网站管理员工具 (GET) 数据?

使用 Pyramid 导出python unicode csv

javascript - 将文本文件读入node.js