How to generate CSV files in Node.js

Generating CSV files is essential for Node.js applications that export data for spreadsheets, reports, or data interchange. As the creator of CoreUI with over 11 years of Node.js development experience since 2014, I’ve implemented CSV export functionality in countless enterprise applications. The most effective solution is to use the fast-csv library or build a simple CSV generator that converts data arrays to CSV format. This approach handles edge cases like quotes and commas while providing efficient file generation.

Use the fast-csv library to generate CSV files in Node.js.

const express = require('express')
const { format } = require('@fast-csv/format')
const fs = require('fs')
const path = require('path')

const app = express()

app.get('/export/csv', async (req, res) => {
  const data = [
    { id: 1, name: 'John Doe', email: '[email protected]', age: 30 },
    { id: 2, name: 'Jane Smith', email: '[email protected]', age: 25 },
    { id: 3, name: 'Bob Johnson', email: '[email protected]', age: 35 }
  ]

  const filename = `export-${Date.now()}.csv`
  const filepath = path.join(__dirname, 'exports', filename)

  const writeStream = fs.createWriteStream(filepath)
  const csvStream = format({ headers: true })

  csvStream.pipe(writeStream)

  data.forEach(row => csvStream.write(row))
  csvStream.end()

  writeStream.on('finish', () => {
    res.download(filepath, filename, (err) => {
      if (err) {
        console.error('Download error:', err)
      }
      fs.unlinkSync(filepath)
    })
  })

  writeStream.on('error', (error) => {
    console.error('Write error:', error)
    res.status(500).json({ error: 'Failed to generate CSV' })
  })
})

First, install fast-csv with npm install @fast-csv/format. The format() function creates a CSV stream that automatically handles headers, quotes, and escaping. The stream is piped to a file write stream for efficient memory usage with large datasets. After the file is written, res.download() sends it to the client and the temporary file is deleted. The headers option automatically extracts column names from object keys.

Best Practice Note

This is the same CSV generation approach we use in CoreUI backend systems for data export features. For simple use cases without dependencies, you can manually build CSV strings, but ensure proper escaping of quotes and commas. For large datasets, always use streaming to avoid loading all data into memory simultaneously.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team