Exploring the functionalities of the read and write stream in csv-parse

Hey everyone, I'm new here and feeling a bit confused about how to properly use readstream and writestream. Currently, I'm attempting this (using the library https://www.npmjs.com/package/csv-parse)

    fs.createReadStream(path.join(__dirname,"../demofile/Customers.csv"))
        .pipe(parse(options))
        .on('data', function(csvrow) {
            console.log(csvrow);
            //do something with csvrow
            output.push(csvrow);        
        })
        .on('end',function() {
        //do something wiht csvData
        console.log(csvData);
        });

However, I don't believe this is the correct way to utilize read and write stream with csv-parse. Can anyone suggest a better approach for using read and write in conjunction with the above code? Essentially, my goal is to read a CSV file and write it into another CSV file. The reason I am specifically looking to use read and write streams is because the file size is approximately 2GB.

Answer №1

In this piece of code, I utilized streams to introduce a new column into a file. The size of the file that was processed was around 500MB, and the maximum RAM usage during the operation did not exceed 50MB. It's worth mentioning that instead of using csv-parse, I opted for importing csv, which acts as an inclusive module encompassing csv-parse, csv-generate, stream-transform, and csv-stringify.

const fs = require('fs');
const csv = require('csv');
const path = require('path');
const EOL = require('os').EOL;

FILE = path.join(__dirname, 'INPUT.csv');
NEW_FILE = path.join(__dirname, 'OUTPUT.csv');

const readStream = fs.createReadStream(FILE);
const writeStream = fs.createWriteStream(NEW_FILE);

const parse = csv.parse();

const transform = csv.transform((row, callback) => {
    row.push('ADDITIONAL_COLUMN');
    output = row.join(',') + EOL;
    callback(null, result);
});

readStream.pipe(parse).pipe(transform).pipe(writeStream);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to synchronize global packages across multiple computers using npm

After installing several npm global packages on my work computer, I am now looking to synchronize these packages with another device. In a typical project, we utilize a package.json file to keep track of package details, making it easy to install all the ...

How can I retrieve documents in MongoDB with <field_key> as <field_value>?

After doing some investigation, I have come across methods to address this issue using mongoDB's $mapReduce feature. However, I have not yet been successful in implementing it.. Here is the data I am working with: [ { _id: '1', de ...

Encountering difficulties retrieving form data in NodeJS Express

I'm currently facing an issue with my form where I am trying to fetch data from the server using ejs templating in my node app. Everything seems fine as there are no errors displayed, but unfortunately, I am unable to retrieve the data in the console. ...

Exploring the mechanics of form data handling with node, express, and jade

What are some best practices for processing HTML form data using Express and Jade templates? I was considering implementing a self-calling loop similar to PHP in the router script, where there are two handlers for the same route - one for GET requests and ...

Managing a large number of records in a for loop on a Node.js server can be challenging, especially when dealing with nearly

After setting up a NodeJS server and connecting it to a MySQL database with around 5000 users, I needed to read the data from MySQL and update a MongoDB database. I managed to write code for this process. https://gist.github.com/chanakaDe/aa9d6a511070c3c78 ...

Dealing with Header Issues in Express: Avoiding Sending Headers Multiple Times!

Encountering an issue with express while working on this code: appToken.post('/getToken', function(req, res) { console.log("Received a request to generate a token"); console.log("Cookie : "+req.headers.cook ...

What is the process for requiring web workers in npm using require()?

I have a setup using npm and webpack, and a part of my application requires Web Workers. The traditional way to create web workers is by using the syntax: var worker = new Worker('path/to/external/js/file.js'); In my npm environment, this metho ...

Retrieve the URL with a GET request and remove a specific object

Currently, I am working on developing a CRUD (Create, Read, Update, Delete) App using Express and LowDB. So far, I have successfully implemented the create and read functions, but I am facing issues with the delete function. This is an example of what th ...

Creating a nested object in Node.js using parent IDs

During my internship, I have been tasked with constructing a nested object using parent IDs without utilizing a children attribute array. Initially, I employed the npm package flatnest for a single-level hierarchy; however, the challenge lies in adapting t ...

A guide on retrieving information from a deeply nested object using pug

Is there a way to access data from a nested JSON object without the use of JavaScript in PUG? I need to loop through product highlights and extract the heading property. JSON FORMAT [{"id":"0.33454785604755677","title":"Product 2 Title", "hig ...

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Nodejs App cannot be started locally due to a directory import issue

My journey to deploy my app on Heroku has hit a roadblock. The import statements, like import cors from 'cors', are causing the app to fail in production with the "Cannot Load ES6 Modules in Common JS" error. Interestingly, everything runs smooth ...

When npm run build is executed, Next JS encounters an issue with resolving fs

I developed a web application using Next JS that runs smoothly with npm run dev. However, when I attempted to run it in production mode with npm run build, I encountered the following errors. I tried adjusting the permissions of the node_modules director ...

Enable express to disregard specific URL modifications

I'm currently working on creating a Single Page App using Express. One of the challenges I am facing is that the Express route feature forces the view to be re-rendered every time the URL changes and a GET request is sent to the server. My code typica ...

Tips for troubleshooting or modifying a dependency that exclusively consists of type declaration files

I am currently facing a challenge where I need to access and debug/change the code of one of our dependencies that contains custom Angular components from a separate repository. This particular repository is being included via a self-hosted npm registry wi ...

Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue. When I run console.log(req), the output is as follows: ServerResponse { ... req: IncomingMessage { ... url: '/my-endpoint', method: &a ...

Error connecting to the database occurred due to a network issue with Mongodb on the initial attempt

I am attempting to establish a connection to mongodb atlas but encountering an issue. MongoNetworkError: failed to connect to server [accounting-shard-00-01-6tg4q.mongodb.net:27017] on first connect [MongoNetworkError: connection timed out] mongoose .c ...

Issues with the w3c validator are preventing proper validation due to an unsuccessful SSL connection attempt

Everything seems to be running smoothly on my website when viewed in the browser. However, when I try to validate it using the W3C validator, I keep encountering an error message. https://i.stack.imgur.com/IGOA0.png Before reaching out here for help, I s ...

DELETE requests will have an empty body, while POST requests of the same kind will contain a body

Recently, I've been working on a small side project intermittently and decided to use Express as the backend for it, even though I'm not very familiar with it. However, I encountered an issue where the body is not being passed when I use the DELE ...

Discover the step-by-step process of combining an array with JSON to create the desired outcome

I am working with a JSON array that looks like this: var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 } Alongside, I have another array: var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' }, ...

What is the process for sending text messages in a local dialect using node.js?

Having an issue with sending bulk SMS using the textlocal.in API. Whenever I try to type a message in a regional language, it displays an error: {"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"} Is there a workaround for se ...