CSV

Read from and write to the CSV files

Introduction

We already know that converting spreadsheet, excel files into the CSV format is very easy.
This library will help NodeJS developers to manage the CSV files.

csv

Properties

Property Description Type Default
filePath realtive or absolute CSV file path string ' '
encoding character encoding (read more) string utf8
mode file mode (read more) number 0o664
fields active CSV fields string[] ['name', 'url', 'path']
fieldDelimiter field delimiter string ,
rowDelimiter row delimiter string \n

Instance


        const csvOpts = {
          filePath: output_file,
          encoding: 'utf8',
          mode: 0o644,

          fields: ['name', 'url', 'picture'],
          fieldDelimiter: ',',
          rowDelimiter: '\n'
        };
        const csv = new CSV(csvOpts);

        await csv.createFile();
        await csv.addHeader();
        

Methods

createFile()

Create CSV file if it does not exist.
If the file that is requested to be created is in directories that do not exist, these directories are created.
If the file already exists, it is NOT MODIFIED.
csv.createFile();

addHeader()

Add fields into the CSV Header. Fields are defined with csvOpts.fields property.
CAUTION: Old content is deleted so only headers will exist in the CSV file after this method is used.
csv.addHeader();

writeRows(rows)

Write multiple CSV rows. Old content will be overwritten when this method is used.
csv.writeRows();

appendRows(rows)

Append multiple CSV rows. New content will be added to the old content.
csv.appendRows(rows);

readRows()

Read CSV rows and convert it into the array of objects.
csv.readRows();

Practical Examples

1. prepare CSV instance


module.exports = async (x, lib) => {
  const output_file = lib.input.output_file;
  const CSV = lib.CSV;
  const echo = lib.echo;

  const csvOpts = {
    filePath: output_file,
    encoding: 'utf8',
    mode: 0o644,

    fields: [
      'name', 'url', 'picture', 'connections',
      'activity_period_days',
      'articles_in_period', 'article_recent_title', 'article_recent_date',
      'posts_in_period', 'post_recent_txt', 'post_recent_date'],
    fieldDelimiter: ',',
    rowDelimiter: '\n'
  };
  const csv = new CSV(csvOpts);

  await csv.createFile();
  await csv.addHeader();

  echo.log('Output CSV file created and header is added.');

  lib.csv = csv;

  return x;

};

2. add new row into the CSV


module.exports = async (x, lib) => {
  const echo = lib.echo;
  const csv = lib.csv;

  echo.log(`Saving data ...`);

  await csv.appendRows([x.currentDataObject]);

  echo.log('Saved data.');


  return x;
};