Skip to content

ParseCSV / FormatCSV (CSV data) ​

SyncJS provides two functions for working with CSV (Comma-Separated Values) data according to RFC 4180.

NOTE

These functions are available as of Syncplify Server! v7.1.1. If you are running an older version, upgrade to the most recent version to use them.

ParseCSV ​

ts
function ParseCSV(text: string, delimiter?: string): string[][];

Parses a CSV string and returns a two-dimensional array of strings (an array of rows, where each row is an array of field values). Quoted fields, embedded commas, and embedded newlines are all handled correctly.

ParameterTypeRequirementExplanation
textstringrequiredThe CSV text to parse
delimiterstringoptionalSingle-character field delimiter. Defaults to , (comma).
Return valueExplanation
string[][]Two-dimensional array of field values
nullThe input could not be parsed as CSV

Example ​

ts
var csv  = 'Alice,30,Engineer\nBob,25,Designer\n';
var rows = ParseCSV(csv);
for (var i = 0; i < rows.length; i++) {
  Log(rows[i][0] + ' is ' + rows[i][1] + ' years old.');
}
// Alice is 30 years old.
// Bob is 25 years old.

Tab-separated example ​

ts
var tsv  = 'col1\tcol2\tcol3\n1\t2\t3\n';
var rows = ParseCSV(tsv, '\t');

FormatCSV ​

ts
function FormatCSV(rows: string[][], delimiter?: string): string;

Serializes a two-dimensional array of strings to a CSV string. Fields are quoted automatically when they contain the delimiter, a double-quote, or a newline character, as required by RFC 4180.

ParameterTypeRequirementExplanation
rowsstring[][]requiredTwo-dimensional array of field values
delimiterstringoptionalSingle-character field delimiter. Defaults to , (comma).
Return valueExplanation
stringThe CSV-formatted text

Example ​

ts
var rows = [
  ['Name', 'Age', 'Role'],
  ['Alice', '30', 'Engineer'],
  ['Bob', '25', 'Designer']
];
var csv = FormatCSV(rows);
WriteTextToFile('/var/reports/people.csv', csv);

Read, transform, and write a CSV file ​

ts
var raw  = ReadTextFile('/var/inbox/data.csv');
var rows = ParseCSV(raw);

// Add a new column header and value
rows[0].push('Processed');
for (var i = 1; i < rows.length; i++) {
  rows[i].push('yes');
}

WriteTextToFile('/var/outbox/data.csv', FormatCSV(rows));