UNPKG

jtc-utils

Version:
78 lines (77 loc) 2.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CsvWriter = void 0; const utf8_cjs_1 = require("./charset/utf8.cjs"); class CsvWriter { writer; encoder; bom; fieldSeparator; lineSeparator; quoteAll; index = 0; constructor(dest, options) { const charset = options?.charset ?? utf8_cjs_1.utf8; this.fieldSeparator = options?.fieldSeparator ?? ","; this.lineSeparator = options?.lineSeparator ?? "\r\n"; this.quoteAll = options?.quoteAll ?? false; this.bom = charset.isUnicode() ? (options?.bom ?? true) : false; this.encoder = charset.createEncoder({ fatal: options?.fatal ?? true, }); let stream; if (dest instanceof WritableStream) { stream = Promise.resolve(dest); } else { const writable = "createWriteStream" in dest ? dest.createWriteStream() : dest; if ("constructor" in writable && "toWeb" in writable.constructor && typeof writable.constructor.toWeb === "function") { stream = Promise.resolve(writable.constructor.toWeb(writable)); } else { throw new TypeError(`Unsuppoted destination: ${dest}`); } } this.writer = stream.then((value) => value.getWriter()); } async write(record, options) { const quoteAll = options?.quoteAll ?? this.quoteAll; let str = ""; if (this.bom) { str = "\uFEFF"; this.bom = false; } for (let i = 0; i < record.length; i++) { const item = `${record[i] ?? ""}`; if (i > 0) { str += this.fieldSeparator; } if (quoteAll || item.includes(this.fieldSeparator) || /[\r\n]/.test(item)) { str += `"${item.replaceAll('"', '""')}"`; } else { str += item; } } str += this.lineSeparator; this.index++; const writer = await this.writer; await writer.write(this.encoder.encode(str)); } get count() { return this.index; } async close() { const writer = await this.writer; if (this.bom) { await writer.write(this.encoder.encode("\uFEFF")); this.bom = false; } await writer.close(); } } exports.CsvWriter = CsvWriter;