* Converts an array of objects into a CSV file.
| 8 | * Converts an array of objects into a CSV file. |
| 9 | */ |
| 10 | class ObjectsToCsv { |
| 11 | /** |
| 12 | * Creates a new instance of the object array to csv converter. |
| 13 | * @param {object[]} objectArray |
| 14 | */ |
| 15 | constructor(objectArray) { |
| 16 | if (!Array.isArray(objectArray)) { |
| 17 | throw new Error('The input to objects-to-csv must be an array of objects.'); |
| 18 | } |
| 19 | |
| 20 | if (objectArray.length > 0) { |
| 21 | if (objectArray.some(row => typeof row !== 'object')) { |
| 22 | throw new Error('The array must contain objects, not other data types.'); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | this.data = objectArray; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Saves the CSV file to the specified file. |
| 31 | * @param {string} filename - The path and filename of the new CSV file. |
| 32 | * @param {object} options - The options for writing to disk. |
| 33 | * @param {boolean} [options.append] - Whether to append to file. Default is overwrite (false). |
| 34 | * @param {boolean} [options.bom] - Append the BOM mark so that Excel shows |
| 35 | * @param {boolean} [options.allColumns] - Whether to check all items for column names or only the first. Default is the first. |
| 36 | * Unicode correctly. |
| 37 | */ |
| 38 | async toDisk(filename, options) { |
| 39 | if (!filename) { |
| 40 | throw new Error('Empty filename when trying to write to disk.'); |
| 41 | } |
| 42 | |
| 43 | let addHeader = false; |
| 44 | |
| 45 | // If the file didn't exist yet or is empty, add the column headers |
| 46 | // as the first line of the file. Do not add it when we are appending |
| 47 | // to an existing file. |
| 48 | const fileNotExists = !fs.existsSync(filename) || fs.statSync(filename).size === 0; |
| 49 | if (fileNotExists || !options || !options.append) { |
| 50 | addHeader = true; |
| 51 | } |
| 52 | |
| 53 | const allColumns = options && options.allColumns |
| 54 | ? options.allColumns |
| 55 | : false; |
| 56 | |
| 57 | let data = await this.toString(addHeader, allColumns); |
| 58 | // Append the BOM mark if requested at the beginning of the file, otherwise |
| 59 | // Excel won't show Unicode correctly. The actual BOM mark will be EF BB BF, |
| 60 | // see https://stackoverflow.com/a/27975629/6269864 for details. |
| 61 | if (options && options.bom && fileNotExists) { |
| 62 | data = '\ufeff' + data; |
| 63 | } |
| 64 | |
| 65 | if (options && options.append) { |
| 66 | return new Promise((resolve, reject) => { |
| 67 | fs.appendFile(filename, data, 'utf8', (error) => { |
nothing calls this directly
no outgoing calls
no test coverage detected