Skip to content

Instantly share code, notes, and snippets.

@nkhil
Created April 20, 2023 11:13
Show Gist options
  • Save nkhil/f108454c78320b6f7bad357c823a9b47 to your computer and use it in GitHub Desktop.
Save nkhil/f108454c78320b6f7bad357c823a9b47 to your computer and use it in GitHub Desktop.
Parse a csv file in node without additional dependencies

Parse a CSV file in node without dependencies

We're going to parse a file, use a conditional to add a new column, then save the new file with an additional column all without using any external dependencies not included in the standard lib

const fs = require('fs');

const inputCsvFile = 'input.csv';
const outputCsvFile = 'output.csv';

const csv = fs.readFileSync(inputCsvFile, 'utf-8');

const rows = csv.split('\n');

for (let i = 0; i < rows.length; i++) {
  const row = rows[i];

  const columns = row.split(',');
  const [, columnTwo] = columns;

  if (columnTwo !== undefined && columnTwo.includes('some-string-conditional')) {
    columns.push('some-value');
  }

  const newRow = columns.join(',');

  rows[i] = newRow;
}

const newCsv = rows.join('\n');

fs.writeFileSync(outputCsvFile, newCsv, 'utf-8');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment