Working with CSV in Node.js: csv-parser and csv-writer libraries
CSV (Comma-Separated Values) is one of the most popular formats for storing and exchanging tabular data. In the Node.js ecosystem, there are many tools for working with this format. In this article, we will look at two of the most convenient and lightweight libraries: csv-parser for reading and csv-writer for writing CSV files.
Installing the libraries
To get started, install both libraries via npm:
npm install csv-parser csv-writerReading CSV files with csv-parser
The csv-parser library converts CSV data into a stream of JavaScript objects. It works based on Node.js Streams, which allows efficient processing of even very large files without loading them entirely into memory.
Basic reading example
Let's create a file users.csv with the following content:
name,age,cityAnna,28,MoscowIvan,35,Saint PetersburgMaria,22,KazanNow let's read it using csv-parser:
const fs = require('fs');const csv = require('csv-parser');
const results = [];
fs.createReadStream('users.csv') .pipe(csv()) .on('data', (data) => results.push(data)) .on('end', () => { console.log('Records read:', results.length); console.log('First record:', results[0]); // Output: { name: 'Anna', age: '28', city: 'Moscow' } });Configuring delimiter and headers
csv-parser supports various settings. For example, if your CSV uses a semicolon as a delimiter:
fs.createReadStream('users.csv') .pipe(csv({ separator: ';' })) .on('data', (row) => console.log(row));If the file has no headers, you can specify them manually:
fs.createReadStream('data.csv') .pipe(csv({ headers: ['id', 'product', 'price'] })) .on('data', (row) => console.log(row));Writing CSV files with csv-writer
The csv-writer library allows you to create CSV files from arrays of objects. It supports various encodings and delimiters.
Creating a simple CSV file
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({ path: 'output.csv', header: [ { id: 'name', title: 'Name' }, { id: 'age', title: 'Age' }, { id: 'city', title: 'City' } ]});
const records = [ { name: 'Anna', age: 28, city: 'Moscow' }, { name: 'Ivan', age: 35, city: 'Saint Petersburg' }, { name: 'Maria', age: 22, city: 'Kazan' }];
csvWriter.writeRecords(records) .then(() => console.log('CSV file successfully created'));Additional csv-writer settings
You can change the field delimiter, add a BOM for correct display of Cyrillic in Excel, and specify the encoding:
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({ path: 'output_utf8.csv', header: [ { id: 'name', title: 'Name' }, { id: 'age', title: 'Age' } ], fieldDelimiter: ';', alwaysQuote: true, encoding: 'utf8'});Practical example: converting JSON to CSV
Often there is a task to convert JSON data to CSV format. Here is a complete example:
const fs = require('fs');const createCsvWriter = require('csv-writer').createObjectCsvWriter;
// Source dataconst jsonData = [ { id: 1, product: 'Laptop', price: 75000, quantity: 10 }, { id: 2, product: 'Mouse', price: 1500, quantity: 50 }, { id: 3, product: 'Keyboard', price: 3500, quantity: 30 }];
// CSV writer configurationconst csvWriter = createCsvWriter({ path: 'products.csv', header: [ { id: 'id', title: 'ID' }, { id: 'product