It treats each element in the array as an array, so '456' is treated as an array with the elements 4,5,6.

A strange workaround I did was to loop through the array and put each element inside its own array, so it would be:

var newArray = [];

 for( var i = 0; i < tempArray.length; i++){
 var arr = [];
 arr.push(tempArray[i]);
newArray.push(arr);
}

And then write the "newArray".

But otherwise if you write row by row, you can put each element inside a bracket, like:

var fast_csv = fastcsv.createWriteStream();
var writeStream = fs.createWriteStream("outputfile.csv");
fast_csv.pipe(writeStream);

for(var i = 0; i < tempArray.length; i++){
    fast_csv.write( [ tempArray[i]  ] );             //each element inside bracket
    }
fast_csv.end();
Answer from Galivan on Stack Overflow
🌐
C2fo
c2fo.github.io › fast-csv
Fast-CSV | Fast-CSV
CSV Parser and Formatter · Get Started · Built on top of the Node.js Stream API, so you can work with APIs you are familiar with. Out of the box formatting and parsing of any delimiter separated file.
🌐
npm
npmjs.com › package › fast-csv
fast-csv - npm
May 6, 2026 - CSV parser and writer. Latest version: 5.0.7, last published: 2 months ago. Start using fast-csv in your project by running `npm i fast-csv`. There are 958 other projects in the npm registry using fast-csv.
      » npm install fast-csv
    
Published   May 06, 2026
Version   5.0.7
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Leanylabs
leanylabs.com › blog › js-csv-parsers-benchmarks
JavaScript CSV Parsers Comparison
We’ve decided to add a baseline String.split test here. It just loads the whole file in memory, splits it into lines, and then breaks every line to separate column values. It’s is one of the fastest ways to parse non-quoted CSV files.
🌐
DEV Community
dev.to › chriscmuir › fast-csv-for-csv-files-21a1
fast-csv for CSV files - DEV Community
March 6, 2021 - In looking at the feature set, fast-csv is comprised of 'parse' and 'format' routines for ingesting and transforming CSV files. It also supports streams for fast processing of large files.
🌐
C2fo
c2fo.github.io › fast-csv › docs › parsing › examples
Examples | Fast-CSV
JavaScript · Output · Copy · import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'a1\tb1', 'a2\tb2' ].join(EOL); const stream = parse({ delimiter: '\t' }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); If you expect the first line your CSV to be headers you may pass in a headers option.
🌐
OneSchema
oneschema.co › blog › top-5-javascript-csv-parsers
Top 5 Javascript CSV Parsers
Fast-csv is laser-focused on performance. It handles parsing large CSVs through the Node.js Streams API, but also supports promises if that’s your pattern of choice.
Find elsewhere
🌐
Snyk
snyk.io › advisor › fast-csv › fast-csv code examples
Top 5 fast-csv Code Examples | Snyk
const fs = require('fs'); const csv = require('fast-csv'); require('sepia'); /* eslint import/no-extraneous-dependencies: [0] */ require('dotenv').config(); const twitter = require('../common/lib/twitter'); // const { getRank } = require('../common/lib/similarweb.js'); const filename = './common/data/dapps.csv'; const apps = []; csv .fromPath(filename, { headers: true, }) .on('data', async (data) => { apps.push(data); }) .on('end', async () => { await twitter.fetchMentions(apps); const writeStream = fs.createWriteStream('./common/data/dapps-ranked.csv'); csv.write(apps, { headers: true }).pipe(writeStream); console.log('done'); });
🌐
GitHub
github.com › C2FO › fast-csv
GitHub - C2FO/fast-csv: CSV parser and formatter for node · GitHub
Fast-csv is library for parsing and formatting CSVs or any other delimited value file in node.
Starred by 1.8K users
Forked by 216 users
Languages   TypeScript 99.0% | JavaScript 1.0%
Top answer
1 of 4
14

Well, I know that this question has been asked a long back but just now I got to work with CSV file for creating API with node js. Being a typical programmer I googled "Reading from a file with fast-csv and writing into an array" well something like this but till date, there isn't any proper response for the question hence I decided to answer this.

Well on is async function and hence execution will be paused in main flow and will be resumed only after nonasync function gets executed.

var queryParameter = ()=> new Promise( resolve =>{
   let returnLit = []
   csv.fromPath("<fileName>", {headers : true})
      .on('data',(data)=>{
          returnLit.push(data[<header name>].trim())
      })
      .on('end',()=>{
          resolve(returnLit)
      })
})
var mainList = [];
queryParameter().then((res)=>mainList = res)

If you want to validate something pass argument into queryParameter() and uses the argument in validate method.

2 of 4
8

The "on data" callback is asynchronous, and the commands that follow the callback will run before the callback finishes. This is why the code does not work, and this reasoning has been pointed out by others who have posted answers and comments.

As for a good way to accomplish the task, I have found that using the "on end" callback is a good fit; since the intention here is to "do something" with the whole data, after the file has been read completely.

var dataArr = [];
csv.fromPath("datas.csv", {headers: true})
.on("data", data => {
  dataArr.push(data);
})
.on("end", () => {
  console.log(dataArr.length);
  // > 4187
});
🌐
GitHub
gist.github.com › basperheim › 1a230cdbcbc5dd54d9145e59d4f1df72
Create a CSV file using NodeJS and fast-csv · GitHub
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const path = require('path'); const csv = require('fast-csv'); /** * Writes data stored in an object literal to a CSV file path **/ const createCsv = (data, filename) => { const csvFile = path.resolve(__dirname, filename); // pass the array of headers to format() method const csvStream = csv.format({ headers: data.headers }); // loop over nested row arrays const arr = data.rows; for (let i = 0; i<arr.length; i++) { let row = arr[i]; csvStream.write( row ); } csvStream.end(); csvStream.pipe(fs.createWriteStream(csvFile, { encoding: 'utf8' } )) return `Finished writing data to: ${csvFile}`; } const data = { headers: ['Col 1', 'Col 2'], rows: [ ['Foo', 'Bar'], ['Hello', 'World'], ['Life', 42], ['Test 1', 'Test 2'] ] }; const result = createCsv(data, 'test.csv'); console.log(result);
🌐
npm
npmjs.com › package › @fast-csv › parse
fast-csv/parse
May 6, 2026 - fast-csv package to parse CSVs. Install Guide · To get started with @fast-csv/parse check out the docs · csv · parse · fast-csv · parser · npm i @fast-csv/parse · github.com/C2FO/fast-csv · c2fo.github.io/fast-csv/docs/parsing/getting-started · 7,027,712 · 5.0.7 ·
      » npm install @fast-csv/parse
    
Published   May 06, 2026
Version   5.0.7
Top answer
1 of 1
2

I was able to find a solution in fast-csv issues section. A good person doug-martin, provided this gist, on how you can do efficiently this kind of operation via Transform stream:

const path = require('path');
const fs = require('fs');
const { Transform } = require('stream');
const csv = require('fast-csv');

class PersistStream extends Transform {
    constructor(args) {
        super({ objectMode: true, ...(args || {}) });
        this.batchSize = 100;
        this.batch = [];
        if (args && args.batchSize) {
            this.batchSize = args.batchSize;
        }
    }

    _transform(record, encoding, callback) {
        this.batch.push(record);
        if (this.shouldSaveBatch) {
            // we have hit our batch size to process the records as a batch
            this.processRecords()
                // we successfully processed the records so callback
                .then(() => callback())
                // An error occurred!
                .catch(err => err(err));
            return;
        }
        // we shouldnt persist so ignore
        callback();
    }

    _flush(callback) {
        if (this.batch.length) {
            // handle any leftover records that were not persisted because the batch was too small
            this.processRecords()
                // we successfully processed the records so callback
                .then(() => callback())
                // An error occurred!
                .catch(err => err(err));
            return;
        }
        // no records to persist so just call callback
        callback();
    }

    pushRecords(records) {
        // emit each record for down stream processing
        records.forEach(r => this.push(r));
    }

    get shouldSaveBatch() {
        // this could be any check, for this example is is record cont
        return this.batch.length >= this.batchSize;
    }

    async processRecords() {
        // save the records
        const records = await this.saveBatch();
        // besure to emit them
        this.pushRecords(records);
        return records;
    }

    async saveBatch() {
        const records = this.batch;
        this.batch = [];
        console.log(`Saving batch [noOfRecords=${records.length}]`);
        // This is where you should save/update/delete the records
        return new Promise(res => {
            setTimeout(() => res(records), 100);
        });
    }
}

const processCsv = ({ file, batchSize }) =>
    new Promise((res, rej) => {
        let recordCount = 0;
        fs.createReadStream(file)
            // catch file read errors
            .on('error', err => rej(err))
            .pipe(csv.parse({ headers: true }))
            // catch an parsing errors
            .on('error', err => rej(err))
            // pipe into our processing stream
            .pipe(new PersistStream({ batchSize }))
            .on('error', err => rej(err))
            .on('data', () => {
                recordCount += 1;
            })
            .on('end', () => res({ event: 'end', recordCount }));
    });

const file = path.resolve(__dirname, `batch_write.csv`);
// end early after 30000 records
processCsv({ file, batchSize: 5 })
    .then(({ event, recordCount }) => {
        console.log(`Done Processing [event=${event}] [recordCount=${recordCount}]`);
    })
    .catch(e => {
        console.error(e.stack);
    });

https://gist.github.com/doug-martin/b434a04f164c81da82165f4adcb144ec

🌐
LogRocket
blog.logrocket.com › home › a complete guide to csv files in node.js
A complete guide to CSV files in Node.js - LogRocket Blog
August 14, 2024 - This guide covers working with CSVs in Node.js, using popular packages like csv-parser, Papa Parse, and Fast-CSV.
🌐
Npmdoc
npmdoc.github.io › node-npmdoc-fast-csv › build › apidoc.html
CSV parser and writer
... console.log(data); }) .on("end", function(){ console.log("done"); }); ``` **`.fromString(string[, options])`** This method parses a string ```javascript var csv = require("fast-csv"); var CSV_STRING = 'a,b\n' + ...
🌐
Papa Parse
papaparse.com
Papa Parse - Powerful CSV Parser for JavaScript
// Parse CSV string var data = ... Papa.parse(bigFile, { worker: true, step: function(results) { console.log("Row:", results.data); } }); Demo Docs FAQ · Papa Parse 5 · GitHub Help · Version · 5.0 · Now the fastest JavaScript CSV parser for the browser ·...
🌐
JavaScript in Plain English
javascript.plainenglish.io › fast-csv-parser-with-node-js-d3cf84d8a0a6
Parse CSV files using Node-JS. Easily parse your input CSV files in… | by Sristi Chowdhury | JavaScript in Plain English
September 15, 2023 - Parse CSV files using Node-JS Easily read and write .csv files with fast-csv in Node JS To see the contents of a user uploaded CSV File, we need to parse the CSV. Few libraries that we can use to …
🌐
GitHub
github.com › knrz › CSVjs
GitHub - CyrusNuevoDia/CSV.js: A simple, blazing-fast CSV parser and encoder. Full RFC 4180 compliance. · GitHub
Simple, blazing-fast CSV parsing/encoding in JavaScript.
Starred by 1.5K users
Forked by 96 users
Languages   JavaScript