Wait until Filestream has finished

Viewed 145

I'm trying to figure out how to solve this problem:

I have a function that reads a csv, saves it to an array and then returns the array. My problem: It always returns an empty array, since the filestream hasn't finished, before I try to return the array.

const parser = require("csv-parser");
const fs = require("fs");

class CsvConverter {

    constructor() {}

    convert(filePath) {
        console.log(this.getRawCsv(filePath));
        [...]
    }

    getRawCsv(filePath) {
        const results = [];
        fs.createReadStream(filePath)
            .pipe(parser())
            .on("data", (data) => results.push(data));
//          .on("end", () => {});
        return results;
    }
    [...]
}

module.exports = CsvConverter;

I already tried to work with the .on("end", () => {}); callback, but I couldn't find a way to return the results array within the callback function.

Using Promises and the async/await functionality hasn't worked for me either but the reason on that might be, that I'm too unexperienced with this functionality.

Thanks for your help and the possible solutions :)

Kind Regards, Andreas

1 Answers

The convert function is finishing before the getRawCsv function because createFileStream is asynchronous. You can wrap the stream into a promise and then wait for it to finish. I abbreviated you example a bit.

const {createReadStream} = require('fs');

class CsvConverter {

    constructor() {}

    async convert(filePath) {
        const raw = await this.getRawCsv(filePath)
        console.log(raw)
    }

    getRawCsv(filePath) {
        const results = [];
        return new Promise((resolve, reject) => {
            createReadStream(filePath, {encoding: 'utf8'})
                .on('data', data => {
                    results.push(data)
                })
                .on('end', () => {
                    resolve(results);
                })
                .on('error', (err) => {
                    reject(err);
                });
        });
    }
}
Related