Write CSV Files In NodeJS (Very Simple Examples)

Welcome to a quick tutorial and examples of how to write CSV files in NodeJS. Need to generate a CSV report or save some log entries in CSV format?

An easy way to create a CSV file in NodeJS is to:

  • Install the CSV stringify module – npm install csv-stringify.
  • Define the array of data const data = [[1,2], [3,4]];
  • Stringify the array and write it to a CSV file –
    • const fs = require("fs");
    • const csv = require("csv-stringify");
    • csv.stringify(data, (e, o) => fs.writeFileSync("MY.CSV", o));

Yes, it’s that simple, but read on for more examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

WRITE CSV FILES IN NODEJS

All right, let us now get into the examples of creating CSV files in NodeJS.

 

1) WRITE ARRAY TO CSV FILE

1-write-array.js
// (A) LOAD REQUIRED MODULES
// https://www.npmjs.com/package/csv-stringify
const fs = require("fs"),
      csv = require("csv-stringify");

// (B) DATA TO WRITE
var data = [
  ["Apple", "Banana"],
  ["Cherry", "Durian"],
  ["Elderberry", "Fig"]
];

// (C) CREATE CSV FILE
csv.stringify(data, (err, output) => {
  fs.writeFileSync("demoA.csv", output);
  console.log("OK");
});

This is pretty much the “full version” of the introduction snippet. CSV (comma-separated values) is not a mystery, it is pretty much just a long string of data.

  • Columns are separated with commas ,
  • Rows are separated with line breaks \r\n
  • Entries with commas are enclosed in a pair of double quotes "Foo,Bar"

That’s all – The CSV stringify module does this “array to CSV string” for you automatically. All we need to do is save the CSV string into a file. The end.

 

2) WRITE OBJECT TO CSV FILE

2-write-object.js
// (A) LOAD REQUIRED MODULES
// https://www.npmjs.com/package/csv-stringify
const fs = require("fs"),
      csv = require("csv-stringify");

// (B) DATA ARRAY
var data = [
  { ani: "Doge", desc: "Goodest Boy" },
  { ani: "Cate", desc: "Evil" },
  { ani: "Birb", desc: "Happy Wings" }
];

// (C) CREATE CSV FILE
csv.stringify(data, {
  header : true,
  columns : { ani : "Animal", desc : "Description" }
}, (err, output) => {
  fs.writeFileSync("demoB.csv", output);
  console.log("OK");
});

Not much of a difference in this example. If the first row is the header, just specify header : true and the columns columns : { ani : "Animal", desc : "Description" }. CSV stringify will do the rest of the “conversion” once again – We only need to save the output.

 

 

3) WRITE ROW BY ROW

3-write-line.js
// (A) LOAD REQUIRED MODULES
// https://www.npmjs.com/package/csv-stringify
const fs = require("fs"),
      csv = require("csv-stringify");

// (B) DATA ARRAY
var data = [
  ["Alpha", "Beta"],
  ["Charlie", "Delta"],
  ["Echo", "Foxtrot"]
];
 
// (C) WRITE TO FILE ROW BY ROW
for (row of data) {
  console.log(row);
  csv.stringify([row], (err, output) => {
    console.log(row);
    fs.appendFileSync("demoC.csv", output);
  });
}

If you are dealing with a large dataset, it is not recommended to dump a massive array into CSV stringify. For example, exporting data from a database into a CSV file. In this case, it is best to write row by row instead.

P.S. If you need an actual example, check out the “Node import/export MYSQL to CSV” link below.

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Write CSV Files In NodeJS (Very Simple Examples)”

  1. Hello!
    What a wonderful and easily understandable Tutorial – exactly what I was looking for. Thank you!
    I only found one error: in the blue box rather far up, the text says “write csv files in csv”. I think you wanted to say “write csv files in node.js”.
    Thanks again!

Leave a Comment

Your email address will not be published. Required fields are marked *