Parses and formats CSV, TSV and other single-character delimited text.
Downloads / mo 132.6M
Stars 446
Last release 3.0.2
License ISC Strengths Parses and formats CSV/TSV . Convert delimited text into rows and serialize records back to text. Converts row values explicitly . Supply a row conversion function when numbers or dates are required. Limitations Object parsing needs unsafe-eval . Use parseRows when the content security policy blocks generated code. Duplicate column names overwrite values . Use parseRows to retain every value under repeated column names. $ npm install d3-dsv Copy
import { csvParse } from 'd3-dsv';
const rows = csvParse('name,score\nAda,42');
console.log(rows);
d3-dsv examples From open-source projects on GitHub export function csvToGeoJSON(
csv: string,
options: ImportOptions['csvOptions'],
progress: ProgressCb
): Promise<FeatureCollection> {
if (!options) throw new Error('Options should not be undefined');
const { kind, delimiter } = options;
let i = 0;
const rows = dsvFormat(delimiter).parse(csv);
const features: Feature[] = [];
// Preflight checks
switch (kind) {
case 'geojson':
case 'wkt':
case 'polyline':
case 'lonlat': {
break;
}
}
progress({ total: rows.length, done: 0 });
for (const row of rows) {
const castRow: JsonObject = options.autoType
? autoType(row, options)
: (row as JsonObject);
switch (kind) {
case 'lonlat': {
const feature = castRowLonLat(
castRow,
EnforcedLonLatOptions.parse(options)
);
if (feature) {
features.push(feature);
}
break;
}
case 'wkt': {
const feature = castRowWKT(castRow, EnforcedWKTOptions.parse(options));
if (feature) {
features.push(feature);
}
break;
}
case 'geojson': {
const feature = castRowGeoJSON(
castRow,
EnforcedWKTOptions.parse(options)
);
if (feature) {
features.push(feature);
}
break;
}
case 'polyline': {
const feature = castRowPolyline(
castRow,
EnforcedWKTOptions.parse(options)
);
if (feature) {
features.push(feature);
}
break;
}
}
progress({ total: rows.length, done: ++i });
}
return {
type: 'FeatureCollection',
features: features
};
}
Show full example Parses CSV or other delimited files in Node.js.
Downloads / mo 114.0M
Stars 1.8K
Last release 5.0.8
License MIT Strengths Streams large files . Parsing streams rows without holding a large file in memory. Reads headers from the first row . Setting headers to true keys each row by the names in the first row. Limitations Single-character delimiters only . Pick a one-character delimiter such as a semicolon or a tab. $ npm install @fast-csv/parse Copy
import { parseString } from '@fast-csv/parse';
parseString('name,score\nAda,42', { headers: true })
.on('error', console.error)
.on('data', console.log);
@fast-csv/parse examples From open-source projects on GitHub async function parseAsCSV(
text: string,
parseOptions: ParserOptionsArgs,
): Promise<string[][]> {
return new Promise((resolve, reject) => {
const rows: string[][] = [];
parseStringAsCsv(text, parseOptions)
.on('data', (row: string[]) => {
rows.push(row);
})
.on('error', (error) =>
reject(
new Error(
`Unexpected error while parsing CSV: ${error.name}: ${error.message}`,
),
),
)
.on(
'data-invalid',
(row: Row | null, rowCount: number, reason?: string) =>
reject(
new Error(
`Invalid row ${rowCount}: ${
reason ?? 'Unknwon reason'
}: ${JSON.stringify(row ?? '')}`,
),
),
)
.on('end', () => {
resolve(rows);
});
});
}
Show full example Parses CSV into records through streaming, callback, and synchronous APIs.
Downloads / mo 109.4M
Stars 4.3K
Last release 7.0.3
License MIT Strengths Offers streaming and synchronous APIs . Choose streamed records or a direct call returning the complete result. Maps columns to object fields . Read named records using header-derived or explicitly configured columns. Limitations Sync parsing retains every record . Use streaming when the complete input and result exceed available memory. $ npm install csv-parse Copy
import assert from "node:assert";
import { parse } from "csv-parse/sync";
const input = `
"key_1","key_2"
"value 1","value 2"
`;
const records = parse(input, {
columns: true,
skip_empty_lines: true,
});
assert.deepStrictEqual(records, [{ key_1: "value 1", key_2: "value 2" }]);
csv-parse examples From open-source projects on GitHub export async function parseCsvBuffer(
input: Buffer | Uint8Array | string,
delimiter = ','
): Promise<{
headers: string[]
rows: Record<string, unknown>[]
rejections: CsvRejectionSummary
}> {
const { parse } = await import('csv-parse/sync')
const text = decodeCsvText(input)
let headers: string[] = []
const rejections = createCsvRejectionCollector()
const options = csvParseOptions(
delimiter,
(h) => {
headers = h
},
rejections.onSkip
)
// double-cast-allowed: shared csvParseOptions() loses the `columns` literal that drives
// csv-parse's record-vs-string[][] overload, but `columns` is always set so records are objects
const parsed = parse(text, options) as unknown as Record<string, unknown>[]
if (parsed.length === 0) {
throw new OrchestrationError('validation', 'CSV file has no data rows')
}
if (headers.length === 0) {
throw new OrchestrationError('validation', 'CSV file has no headers')
}
return { headers, rows: parsed, rejections: rejections.summary }
}
Show full example Reads and writes Excel workbooks and CSV files.
Downloads / mo 105.0M
Stars 15.5K
Last release 4.4.0
License MIT $ npm install exceljs Copy
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
workbook.csv.readFile('input.csv').then(worksheet => {
console.log(worksheet.rowCount);
});
ExcelJS examples From open-source projects on GitHub const exportCSV = async (workbook: Workbook, fileName: string, isView?: boolean) => {
await workbook.csv.writeBuffer({ encoding: 'UTF-8' }).then((buffer) => {
const blob = new Blob(['\uFEFF' + buffer], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = `${fileName}.csv`;
link.click();
Message.success({
content: isView ? t(Strings.import_view_data_succeed) : t(Strings.import_file_data_succeed),
});
});
};
Show full example Parses delimited text in browsers and Node.js and serializes records back to CSV.
Downloads / mo 96.6M
Stars 13.6K
Last release 5.7.1
License MIT Strengths Detects common delimiters automatically . Leave delimiter blank to infer a separator from the configured candidates. Runs parsing in browser workers . Use worker mode to keep the page responsive during parsing. Limitations Streaming changes completion results . Read streamed rows in step or chunk callbacks, rather than complete. European numbers need normalization . Swap decimal commas and grouping dots before enabling dynamicTyping. $ npm install papaparse Copy
import Papa from 'papaparse';
const result = Papa.parse('name,score\nAda,42', { header: true });
console.log(result.data);
Papa Parse examples From open-source projects on GitHub export default function serialize(
rows: Array<Record<string, unknown>>,
{ columns, header = true }: SerializeOptions = {},
): string {
return papaparse.unparse(rows, { columns, header, escapeFormulae: true });
}
Parses and writes spreadsheet data.
Downloads / mo 60.5M
Stars 36.3K
Last release 0.20.3
License Apache-2.0 Limitations readFile skips browsers . In the browser, pass file data to read instead of a filename. $ npm i --save https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz Copy
import * as XLSX from 'xlsx';
const workbook = XLSX.read('name,score\nAda,42', { type: 'string' });
console.log(workbook.SheetNames);
Converts records into CSV text through the Node.js stream API, with synchronous and callback options.
Downloads / mo 50.3M
Stars 4.3K
Last release 6.9.0
License MIT Strengths Custom formatters and headers . Options set formatters, delimiters, quotes, escape characters, and the header row. No external dependencies . The package installs with no external dependency. Limitations Writes only . Parse CSV with its companion package csv-parse . $ npm install csv-stringify Copy
import { stringify } from "csv-stringify/sync";
import assert from "node:assert";
const output = stringify([
["1", "2", "3", "4"],
["a", "b", "c", "d"],
]);
assert.equal(output, "1,2,3,4\na,b,c,d\n");
csv-stringify examples From open-source projects on GitHub function convertToDsv(data: ExportData, options: ConvertToDsvOptions) {
const { rowIds, access, columns: viewColumns } = data;
const { delimiter, header } = options;
// create formatters for columns
const formatters = viewColumns.map(col => col.formatter);
// Arrange the data into a row-indexed matrix, starting with column headers.
const csvMatrix = [viewColumns.map(col => getExportHeader(col, header))];
// populate all the rows with values as strings
rowIds.forEach((row) => {
csvMatrix.push(access.map((getter, c) => formatters[c].formatAny(getter(row))));
});
return stringifyAsync(csvMatrix, { delimiter });
}
Show full example