Repository navigation
Expand file tree
/
Copy pathto-csv.js
More file actions
94 lines (81 loc) · 2.66 KB
/
Copy pathto-csv.js
File metadata and controls
94 lines (81 loc) · 2.66 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var CsvBuilder = require("csv-builder");
function new_normalizeArray_(data_row) {
var csved_row = data_row.map((column_data) => {
let text_data = column_data != null ? column_data.toString() : '';
if (this.format.delimiter === "\t") {
text_data = text_data.replace(/\t/g, "");
} else if (this.format.delimiter === ",") {
if (
text_data.includes(",") ||
text_data.includes("\n") ||
text_data.includes('"')
) {
if (text_data.includes('"')) {
text_data = text_data.replace(/"/g, '""');
}
text_data = `"${text_data}"`;
}
}
return text_data;
});
return csved_row;
}
// If options.show_headers == false OR undefined then do not return header names in output
function forgetHeader_() {
return "";
}
/**
* Create csv streams from a mongoose schema
* @param {mongoose.Schema} schema
* @param {Object} options CsvBuilder options
* @param {String|Array} options.headers Space separated headers, or array of headers
* @param {String} [options.delimiter = ','] Value delimiter for csv data
* @param {String} [options.terminator = '\n'] Line terminator for csv data
* @param {Object} options.constraints {"header": "prop"}
* @param {Object} options.virtuals Virtual properties.
*/
module.exports = function mongooseToCsv(schema, options) {
// need options.headers
if (!options.headers)
throw new Error("MongooseToCsv requires the `headers` option");
var builder = new CsvBuilder(options);
builder._normalizeArray = new_normalizeArray_;
if (typeof options.show_headers === "undefined" || !options.show_headers) {
builder.getHeaders = forgetHeader_;
}
if (options.virtuals) {
for (var v in options.virtuals) {
builder.virtual(v, options.virtuals[v]);
}
}
/**
* Static Method `csvReadStream`
* @param {Array<Documents>} docs Array of mongoose documents
* @return {Stream} Csv read stream.
*/
schema.static("csvReadStream", function (docs) {
if (!docs) {
throw new Error("[Model].csvReadStream requires an array of documents.");
}
var data = docs.map(function (obj) {
return obj._doc;
});
return builder.createReadStream(data);
});
/**
* Create a Csv stream from a query Object.
* @param {Object} query Mongoose query
* @return {Stream} Csv transform stream
*/
schema.static("findAndStreamCsv", function (query) {
query = query || {};
return this.find(query).cursor().pipe(builder.createTransformStream());
});
/**
* Create a transform stream
* @return {Stream} transform stream
*/
schema.static("csvTransformStream", function () {
return builder.createTransformStream();
});
};