0
0
NodejsHow-ToBeginner · 3 min read

How to Read CSV File in Node.js: Simple Guide with Example

To read a CSV file in Node.js, you can use the built-in fs module to read the file content and then parse it manually or use a library like csv-parser for easier parsing. The csv-parser library streams the file and converts each row into a JavaScript object automatically.
📐

Syntax

Using the csv-parser library, the basic syntax involves creating a readable stream from the CSV file with fs.createReadStream(), then piping it to csv() which parses the CSV data row by row.

  • fs.createReadStream('file.csv'): Opens the CSV file as a stream.
  • csv(): Parses CSV data into JavaScript objects.
  • .on('data', callback): Handles each parsed row.
  • .on('end', callback): Runs after all rows are processed.
javascript
const fs = require('fs');
const csv = require('csv-parser');

fs.createReadStream('file.csv')
  .pipe(csv())
  .on('data', (row) => {
    console.log(row);
  })
  .on('end', () => {
    console.log('CSV file successfully processed');
  });
💻

Example

This example reads a CSV file named data.csv with columns name and age. It prints each row as an object and shows a completion message.

javascript
const fs = require('fs');
const csv = require('csv-parser');

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (row) => {
    console.log(row);
  })
  .on('end', () => {
    console.log('CSV file successfully processed');
  });
Output
{"name":"Alice","age":"30"} {"name":"Bob","age":"25"} CSV file successfully processed
⚠️

Common Pitfalls

Common mistakes when reading CSV files in Node.js include:

  • Not installing or importing the csv-parser library before use.
  • Trying to read large CSV files without streaming, which can cause memory issues.
  • Assuming CSV columns are automatically typed; all values are strings unless converted.
  • Not handling errors on the file stream or parser.

Always handle errors and use streaming for large files.

javascript
const fs = require('fs');
const csv = require('csv-parser');

// Wrong: reading entire file synchronously (bad for large files)
// const data = fs.readFileSync('data.csv', 'utf8');
// console.log(data);

// Right: streaming and parsing
fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (row) => {
    console.log(row);
  })
  .on('error', (err) => {
    console.error('Error reading CSV:', err);
  })
  .on('end', () => {
    console.log('Done processing CSV');
  });
📊

Quick Reference

Summary tips for reading CSV files in Node.js:

  • Use fs.createReadStream() to read files efficiently.
  • Use csv-parser for easy CSV parsing.
  • Handle data, end, and error events.
  • Convert string values to numbers or dates if needed.
  • Install csv-parser with npm install csv-parser before use.

Key Takeaways

Use the csv-parser library with fs.createReadStream() to read CSV files efficiently in Node.js.
Always handle data, end, and error events when streaming CSV files.
CSV values are strings by default; convert types as needed after parsing.
Avoid reading large CSV files synchronously to prevent memory issues.
Install csv-parser via npm before using it in your project.