read and update csv file in nodejs

To read and update a CSV file in Node.js, you can follow these steps:

  1. Install the CSV parser package: You'll need to install the 'csv-parser' package from npm. Open your command line interface and run the following command:
npm install csv-parser
  1. Import the necessary modules: In your Node.js script, import the 'fs' module to work with the file system, and the 'csv-parser' module to parse the CSV file. Add the following lines at the top of your script:
const fs = require('fs');
const csv = require('csv-parser');
  1. Read the CSV file: Use the fs.createReadStream() function to create a readable stream from the CSV file. Pass the file path as an argument. Here's an example:
fs.createReadStream('path/to/file.csv')
  .pipe(csv())
  .on('data', (row) => {
    // Process each row of data here
  })
  .on('end', () => {
    // Code to execute when reading is complete
  });
  1. Process each row of data: Inside the data event listener, you can access each row of data as an object. You can perform any required operations on the data here. For example, you can log it to the console or update values. Here's an example:
.on('data', (row) => {
  console.log(row); // Log each row of data
  // Update values or perform other operations here
})
  1. Update the CSV file: To update the CSV file, you can use the fs.createWriteStream() function to create a writable stream. Pass the file path as an argument. Here's an example:
const writeStream = fs.createWriteStream('path/to/file.csv');
  1. Write data to the file: Inside the data event listener, you can write the updated data to the file using the writeStream.write() function. Here's an example:
.on('data', (row) => {
  // Update values or perform other operations here
  writeStream.write(/ Updated row of data /);
})
  1. Finish writing to the file: After processing all the data, you need to end the writable stream to ensure all the data is written to the file. Add the following line of code after the end event listener:
.writeStream.end();

Make sure to replace 'path/to/file.csv' with the actual path to your CSV file. This should allow you to read and update the CSV file in Node.js.