csv.js
1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
};