Part of the Stream Promises module is the finished function. The Function plugs into a stream and resolves a promise when it is no longer readable, writable or has experienced an error or a premature close event.
The promises example leverages pipe as well as finished to provide a convenient solution to read a file from the file system and to pipe its output into the parser.
This example is available with the command node samples/recipe.promises.js.
import assert from'node:assert';import fs from'node:fs';import os from'node:os';import{ parse }from'csv-parse';// Note, the `stream/promises` module is only available// starting with Node.js version 16import{ finished }from'stream/promises';// Prepare the datasetawait fs.promises.writeFile(`${os.tmpdir()}/input.csv`,['a,b,c','1,2,3'].join('\n'));// Read and process the CSV fileconstprocessFile=async()=>{const records =[];const parser = fs
.createReadStream(`${os.tmpdir()}/input.csv`).pipe(parse({// CSV options if any}));
parser.on('readable',function(){let record;while((record = parser.read())!==null){// Work with each record
records.push(record);}});awaitfinished(parser);return records;};// Parse the CSV contentconst records =awaitprocessFile();// Validate the records
assert.deepStrictEqual(records,[['a','b','c'],['1','2','3']]);