Created
December 30, 2024 05:02
-
-
Save Klrfl/c190db607456b4915ee22e70b0805bae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "node:fs/promises"; | |
/** | |
* read a csv file | |
* @param {string} filename - the name of the CSV file | |
* @param {string} delimiter - delimiter of the CSV file, defaults to ',' | |
* @returns Array<string[]> | |
* */ | |
export default async function parseCSV(filename, delimiter = ",") { | |
const result = await fs.readFile(filename, { encoding: "utf8" }); | |
const rows = []; | |
for (const row of result.split("\n")) { | |
rows.push(row.split(delimiter)); | |
} | |
return rows; | |
} | |
import fs from "node:fs" | |
/** | |
* parse a CSV file with node stream | |
* @param {string} filename - name of file to be read | |
* @returns {Promise<Array<string[]>>} | |
* */ | |
export default function parseCSVWithStream(filename) { | |
return new Promise((resolve, reject) => { | |
const reader = fs.createReadStream(filename, {'encoding': "utf-8"}) | |
let rows = [] | |
reader.on("error", (err) => reject(err)) | |
reader.on("data", (data) => { | |
const row = data.toString().trim() | |
rows.push(row) | |
}) | |
reader.on("end", () => { | |
rows = rows.join("").split("\n") | |
const result = rows.map((row) => row.split(",")) | |
resolve(result) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment