deno-csv
Streaming API for reading and writing CSV for https://deno.land/.
Usage
Reading
Read CSV file
import { readCSV } from "https://deno.land/x/csv/mod.ts";
const f = await Deno.open("./example.csv");
for await (const row of readCSV(f)) {
console.log(`line: ${row.join(' ')}`);
}
f.close();
Read CSV file with custom separators
import { readCSV } from "https://deno.land/x/csv/mod.ts";
const f = await Deno.open("./example.csv");
const options = {
columnSeparator: new TextEncoder().encode(';'),
lineSeparator: new TextEncoder().encode('\r\n'),
quote: new TextEncoder().encode('$'),
};
for await (const row of readCSV(f, options)) {
console.log(`line: ${row.join(' ')}`);
}
f.close();
Read objects from CSV file with header row
import { readCSVObjects } from "https://deno.land/x/csv/mod.ts";
const f = await Deno.open("./example.csv");
for await (const obj of readCSVObjects(f)) {
console.log(obj);
}
f.close();
Writing
Write CSV file
import { writeCSV } from "https://deno.land/x/csv/mod.ts";
const f = await Deno.open("./example.csv", { write: true, create: true, truncate: true });
const rows = [
["a", "b", "c"],
["1", "2", "3"],
];
await writeCSV(f, rows);
f.close();
Write objects asynchronously to CSV file
import { writeCSVObjects } from "https://deno.land/x/csv/mod.ts";
const f = await Deno.open("./example.csv", { write: true, create: true, truncate: true });
const header = ["a", "b", "c"];
const asyncObjectsGenerator = async function*() {
yield { a: "1", b: "2", c: "3" };
yield { a: "4", b: "5", c: "6" };
}
await writeCSVObjects(f, header, asyncObjectsGenerator());
f.close();
Write CSV file manually
import { CSVWriter } from "https://deno.land/x/csv/mod.ts";
const f = await Deno.open("./example.csv", { write: true, create: true, truncate: true });
const writer = new CSVWriter(f, {
columnSeparator: new TextEncoder().encode("\t"),
lineSeparator: new TextEncoder().encode("\r\n"),
});
await writer.writeCell("a");
await writer.writeCell("b");
await writer.writeCell("c");
await writer.nextLine();
await writer.writeCell("1");
await writer.writeCell("2");
await writer.writeCell("3");
f.close();