import { fileURLToPath } from 'node:url';
/** @import { PathLike } from 'node:fs' */
-/**
- * Convert a JavaScript array into a CSV string.
- *
- * @param {Array<string>} arr An array of strings representing one row of a CSV file.
- * @returns {string} A string representing one row of a CSV file, with character escaping and line endings compliant with
- * [RFC 4180](https://www.ietf.org/rfc/rfc4180.txt).
- */
-export function arrayToCSVString(arr) {
- let out = '';
- for (const field of arr) {
- if (/[,"\r\n]/g.test(field)) {
- out += `"${field.replaceAll('"', '""')}",`;
- }
- else {
- out += `${field},`;
- }
- }
- return `${out.slice(0, -1)}\r\n`;
-}
-
/**
* Parse and normalize a `PathLike` object into a string.
*
async write(chunk) {
let data;
try {
- data = arrayToCSVString(JSON.parse(chunk));
+ data = CSVWriter.arrayToCSVString(JSON.parse(chunk));
}
catch {
data = chunk;
}
});
}
+
+ /**
+ * Convert a JavaScript array into a CSV string.
+ *
+ * @param {Array<string>} arr An array of strings representing one row of a CSV file.
+ * @returns {string} A string representing one row of a CSV file, with character escaping and line endings compliant with
+ * [RFC 4180](https://www.ietf.org/rfc/rfc4180.txt).
+ */
+ static arrayToCSVString(arr) {
+ let out = '';
+ for (const field of arr) {
+ if (/[,"\r\n]/g.test(field)) {
+ out += `"${field.replaceAll('"', '""')}",`;
+ }
+ else {
+ out += `${field},`;
+ }
+ }
+ return `${out.slice(0, -1)}\r\n`;
+ }
}
import { pathToFileURL } from 'node:url';
import { csvStreamEqualWritable, csvStreamNotEqualWritable, createCSVMockStream, createTempFile } from './utils.js';
-import { arrayToCSVString, parsePathLike, CSVReader, CSVTransformer, CSVWriter } from '../src/core.js';
+import { parsePathLike, CSVReader, CSVTransformer, CSVWriter } from '../src/core.js';
-suite('arrayToCSVString', { concurrency: true }, () => {
+suite('CSVWriter.arrayToCSVString', { concurrency: true }, () => {
const vectors = [
{ name: 'converts simple row', input: ['abc', '123'], output: 'abc,123\r\n' },
{ name: 'converts row with commas', input: ['a,bc', '12,3'], output: '"a,bc","12,3"\r\n' },
];
for (const { name, input, output } of vectors) {
test(name, { concurrency: true }, () => {
- deepStrictEqual(arrayToCSVString(input), output);
+ deepStrictEqual(CSVWriter.arrayToCSVString(input), output);
});
}
});