How To Write CSV Files In NodeJS (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:

  1. Manually create a string of CSV data.
    • Separate columns using commas – var data = "First,Second"
    • Add new rows using a carriage return and new line – data += "\r\nThird,Forth"
  2. Write the string into a CSV file – require("fs").writeFileSync("FILE.CSV", data)

Yes, it’s that simple. We don’t even need to use third-party modules, but read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Write CSV Useful Bits & Links
The End

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

WRITE CSV FILES IN NODEJS

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

 

1) BASIC WRITE & APPEND TO CSV FILES

1-basic-csv.js
// (A) MANUAL CSV STRING
var csv = "Apple,Banana\r\nCherry,Durian";

// (B) WRITE TO FILE
const fs = require("fs");
fs.writeFileSync("demoA.csv", csv);

// (C) APPEND MORE
csv = "\r\nElderberry,Fig";
fs.appendFileSync("demoA.csv", csv);
console.log("Done!");

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

That’s all. We only need to create a string of CSV data in Node, then write or append it to a file.

 

2) ARRAY TO CSV FILE

2-write-array.js
// (A) DATA ARRAY
var data = [
  ["Asparagus", "Beet"],
  ["Cabbage", "Dill"],
  ["Eggplant", "Fennel"]
];

// (B) TO CSV STRING
var csv = "";
for (let i of data) {
  csv += i.join(",") + "\r\n";
}

// (C) WRITE TO FILE
const fs = require("fs");
fs.writeFileSync("demoB.csv", csv);
console.log("Done!");

How do we write an array to a CSV file? It is as straightforward as can be:

  • The data needs to be arranged in an array of strings, stacked in a nested array.
  • Loop through each row of the nested array – for (let i of data) { ... }
  • Create the CSV data string, join the elements together, add a new line – csv += i.join(",") + "\r\n"
  • That’s all. Write the string to a CSV file.

 

 

3) ARRAY TO CSV FILE (USING FILE STREAM)

3-stream-array.js
// (A) DATA ARRAY
var data = [
  ["Alpha", "Beta"],
  ["Charlie", "Delta"],
  ["Echo", "Foxtrot"]
];

// (B) WRITE TO FILE
const fs = require("fs");
const stream = fs.createWriteStream("demoC.csv");
for (let i of data) { stream.write(i.join(",") + "\r\n"); }
stream.end();
console.log("Done!");

The previous example works, but only for small sets of data. If we have a massive array of data, manually creating the CSV string is going to take up a lot of memory. So here is an alternative – We use a file stream, and write row-by-row instead.

 

4) USING CSV WRITER MODULE

4-object-csv.js
// (A) CSV WRITER MODULE
// npm install csv-writer
// https://www.npmjs.com/package/csv-writer
const createCSV = require('csv-writer').createObjectCsvWriter;

// (B) CREATE NEW CSV DOCUMENT
const csv = createCSV({
  path: "demoD.csv",
  header: [
    {id: "ani", title: "ANIMAL"},
    {id: "desc", title: "DESCRIPTION"}
  ]
});

// (C) WRITE DATA ROWS
csv.writeRecords([
  { ani: "Doge", desc: "Goodest Boy" },
  { ani: "Cate", desc: "Evil" },
  { ani: "Birb", desc: "Happy Wings" }
])
.then(() => { console.log("Done!"); });

Lastly, there are actually quite a number of modules that we can use to create CSV files… We don’t actually need them, but they do somewhat help to deal with complex objects and data sets.

 

 

USEFUL BITS & LINKS

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

 

INFOGRAPHIC CHEAT SHEET

Write CSV Files In NodeJS (Click To Enlarge)

 

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 “How To Write CSV Files In NodeJS (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 *