concept huge csv file in category data

appears as: huge CSV files, huge CSV file
Data Wrangling with JavaScript

This is an excerpt from Manning's book Data Wrangling with JavaScript.

How can we use Node.js streams to transform a huge CSV file? This could be difficult, but fortunately Papa Parse, the library we started using in chapter 3, already has support for reading a Node.js stream.

Figure 7.8 Streaming transformation of a huge CSV file

c07_08.eps
Listing 7.5 Transforming a huge CSV file (listing-7.5.js)
const stream = require('stream');
const openCsvInputStream = require('./toolkit/open-csv-input-stream');
const openCsvOutputStream = require('./toolkit/open-csv-output-stream');

const inputFilePath = "./data/weather-stations.csv";
const outputFilePath = "./output/weather-stations-transformed.csv";

function transformRow (inputRow) { //  #1  

 const outputRow = Object.assign({}, inputRow);    #2  

 if (typeof(outputRow.MinTemp) === "number") {    #3  
 outputRow.MinTemp /= 10;    #3  
 }    #3  
 else {    #3  
 outputRow.MinTemp = undefined;    #3  
 }    #3  

 if (typeof(outputRow.MaxTemp) === "number") {    #3  
 outputRow.MaxTemp /= 10;    #3  
 }    #3  
 else {    #3  
 outputRow.MaxTemp = undefined;    #3  
 }    #3  

 return outputRow;    #4  
};    #1  

function convertTemperatureStream () {    #5  
 const transformStream = new stream.Transform({ objectMode: true });    #6  
 transformStream._transform = (inputChunk, encoding, callback) => {    #7  
 const outputChunk = transformRow(inputChunk);    #8  
 transformStream.push(outputChunk);    #9  
 callback();    #10  
 };    #8  
 return transformStream;    #6  
};    #6  

openCsvInputStream(inputFilePath)    #11  
 .pipe(convertTemperatureStream())    #12  
 .pipe(openCsvOutputStream(outputFilePath))    #13  
 .on("error", err => {    #14  
        console.error("An error occurred while transforming the CSV file.");  
        console.error(err);  
    });  

#1   Transforms a single data record
#2   Clones the record should we prefer not to modify source data
#3   Converts MinTemp and MaxTemp fields from tenths of degrees Celsius to normal degrees Celsius
#4   Returns the transformed data record
#5   Creates a transformation stream that we can pipe our data through
#6   Instantiates a bidirectional Transform stream in object mode
#7   This is a callback that’s invoked as chunks of data pass through the transformation stream.
#8   Applies our transformation to a chunk of data
#9   Forwards the transformed chunk of data to the output stream
#10   Invokes the callback to indicate we have finished transforming the chunk of data. This allows for asynchronous programming.
#11   Opens the readable CSV data stream
#12   Pipes the CSV data stream to the transformation stream
#13   Pipes the transformed stream to the writable CSV data stream
#14   Handles any error that might have occurred