@iwsio/json-csv-node
Version:
ESM/CJS module that easily converts JSON to CSV. This package supports streaming and buffered conversion to CSV.
68 lines (67 loc) • 2.47 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.stream = exports.buffered = exports.checkOptions = void 0;
const nodeStream = require("stream");
const core = require("@iwsio/json-csv-core");
const { buffered: baseBuffered, exporter: { getHeaderRow, getBodyRow, checkOptions: baseCheckOptions } } = core;
const { Transform } = nodeStream;
/**
* Check the options; ensure defaults. This extends core's check options with new, encoding option for streams.
* @param opts
* @returns
*/
const checkOptions = (opts) => {
var _a;
const options = baseCheckOptions(opts);
options.encoding = (_a = opts.encoding) !== null && _a !== void 0 ? _a : 'utf8';
return options;
};
exports.checkOptions = checkOptions;
/**
* Same as the core's buffered function except this returns a promise for async callers rather than classic callback.
* @param data Array of objects to be transformed.
* @param options CSV Options
* @returns Promise resulting in CSV output
*/
const buffered = (data, options) => {
return new Promise((resolve, reject) => {
try {
const result = baseBuffered(data, options);
resolve(result);
}
catch (err) {
reject(err);
}
});
};
exports.buffered = buffered;
/**
* Creates a transform stream that can be uses to pipe readable objects into for conversion to CSV.
* @param opts CSV options
* @returns Tranform stream that converts readable objects to csv string
*/
const stream = (opts) => {
let writtenHeader = false;
const options = (0, exports.checkOptions)(opts);
const { ignoreHeader, fields, encoding } = options;
const transformer = new Transform({
writableObjectMode: true,
transform(chunk, _encoding, callback) {
// debug(`incoming chunk: ${require('util').inspect(chunk)}`)
// debug(encoding)
if (!writtenHeader && !ignoreHeader) {
writtenHeader = true;
const header = getHeaderRow(fields, options.fieldSeparator);
// debug(`writing header ${header}`)
this.push(header);
}
const row = getBodyRow(chunk, fields, options.fieldSeparator);
// debug(`writing row ${require("util").inspect(row)}`)
this.push(row);
callback();
}
});
transformer.setEncoding(encoding);
return transformer;
};
exports.stream = stream;
;