csv.js 1.02 KB
const _ = require('lodash');
const Json2csvParser = require('json2csv').Parser;

const sleep = (time) => {
    return new Promise((resolve) => {
        setTimeout(resolve, time || 1000);
    });
};

const csvExport = async(res, info = {}) => {
    await res.setHeader('Content-disposition', `attachment; filename=${info.fileName}.csv`);
    await res.writeHead(200, {'Content-Type': 'text/csv;charset=utf-8'});

    let fields = info.cols || [];
    let data = [];

    info.rows = info.rows || [];

    const json2csvParser = new Json2csvParser({fields});

    let block = [];

    _.forEach(info.rows, (value) => {
        block.push(_.zipObject(fields, value));

        if (block.length > 4000) {
            data.push(block);
            block = [];
        }
    });

    block.length && data.push(block);

    for (let i = 0; i < data.length; i++) {
        await res.write(json2csvParser.parse(data[i]));
        await sleep(200); // 解决循环写入cpu占用过高
    }

    await res.end();
};

module.exports = {
    csvExport
};