UNPKG

@maukode/siesvi

Version:

siesvi is CSV library that use typescript and provide CSV common functions from parsing, validation, to transformation.

81 lines (80 loc) 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CsvWriter = void 0; const stream_1 = require("stream"); const fs_1 = require("fs"); class CsvWriter extends stream_1.Writable { constructor(options = {}) { super({ objectMode: true }); this.columns = null; this.filePath = null; this.fileStream = null; this.outputBuffer = ''; // Store in-memory output if no filePath this.delimiter = options.delimiter || ','; this.includeHeader = options.includeHeader !== undefined ? options.includeHeader : true; this.filePath = options.filePath || null; } _construct(callback) { try { if (this.filePath) { this.fileStream = (0, fs_1.createWriteStream)(this.filePath, { flags: 'w' }); } callback(); } catch (error) { callback(error); } } _write(chunk, _, callback) { if (this.columns === null) { if (typeof chunk === 'object' && chunk !== null && !Array.isArray(chunk)) { this.columns = Object.keys(chunk); if (this.includeHeader) { this.writeData(this.columns.join(this.delimiter) + '\n'); } } else { return callback(new Error('First chunk must be an object to determine columns.')); } } if (typeof chunk === 'object' && chunk !== null && !Array.isArray(chunk)) { const rowValues = this.columns.map((col) => { let value = chunk[col]; // Access property dynamically if (typeof value === 'string') { if (value.includes('"') || value.includes(this.delimiter)) { value = `"${value.replace(/"/g, '""')}"`; // Escape double quotes } } return value !== undefined && value !== null ? String(value) : ''; // Handle undefined/null }); this.writeData(rowValues.join(this.delimiter) + '\n', callback); } else { callback(new Error('Chunk must be an object.')); } } writeData(data, callback) { if (this.fileStream) { if (!this.fileStream.write(data, callback)) { this.fileStream.once('drain', () => callback && callback()); // Wait for drain event if buffer is full } } else { this.outputBuffer += data; if (callback) callback(); } } _final(callback) { if (this.fileStream) { this.fileStream.end(callback); } else { callback(); } } getOutputBuffer() { return this.outputBuffer; } } exports.CsvWriter = CsvWriter;