How to Write to CSV File | JavaScript and Node.js
CSV (Comma Separated Values) is a popular file format for storing tabular data. In this article, we will discuss how to write to a CSV file using JavaScript and Node.js.
Using Node.js
Node.js is a popular runtime environment for running JavaScript on the server side. To write to a CSV file using Node.js, you can use the fs
module, which provides an API for interacting with the file system.
const fs = require('fs'); const data = [ { name: 'John Doe', age: 30, email: 'john@example.com' }, { name: 'Jane Smith', age: 25, email: 'jane@example.com' } ]; const csv = data.map(row => Object.values(row).join(',')).join('n'); fs.writeFile('output.csv', csv, (err) => { if (err) throw err; console.log('CSV file has been saved'); });
Using Browser-based JavaScript
If you want to write to a CSV file using JavaScript in a web browser, you can use the Blob
and URL
APIs to create and download the file.
const data = [ { name: 'John Doe', age: 30, email: 'john@example.com' }, { name: 'Jane Smith', age: 25, email: 'jane@example.com' } ]; const csv = data.map(row => Object.values(row).join(',')).join('n'); const blob = new Blob([csv], { type: 'text/csv' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'output.csv'; a.textContent = 'Download CSV'; document.body.appendChild(a);
Conclusion
Writing to a CSV file using JavaScript is a common task, and it can be done using both Node.js on the server side and browser-based JavaScript on the client side. With the examples provided in this article, you should be able to create and download CSV files with ease.
how to append data in csv