7

I have this function

function getData(file, type) {
    let data = [];
    fs.createReadStream(file)
        .pipe(csv({headers: false, separator: ';',}))
        .on('data', (row) => {
            let item = {
                date: row[0],
                value: row[1]
            };
            let item2 = {
                date: moment(row[0], "DD-MM-YYYY HH:mm").add(30, "minutes").format("DD/MM/YYYY HH:mm"),
                value: row[2]
            };
            data.push(item);
            data.push(item2);
        })
        .on('end', () => {
           return data;
        });
}

and I would like to return the data parsed in the csv, but when I return data in the .on method, data is empty.

How should I do it ?

2
  • You should listen to .on('error', (err) => { see if you have no issue. Also put the .on('data', (row) => { function into a try/catch Commented Jan 13, 2020 at 10:17
  • What I do right now, instead of returning data, is using a global var, so I know there is no error, right now. So, it doesn't fix the issue, but anyway, I will check it, it is an important variable, you are right ! Commented Jan 13, 2020 at 10:24

1 Answer 1

21

I would suggest using a promise-based approach, you can return a promise from the getData function, then resolve or reject as appropriate.

This keeps things a lot cleaner for the calling function.

For example:

function getData(file, type) {
    let data = [];
    return new Promise((resolve, reject) => {
        fs.createReadStream(file)
            .on('error', error => {
                reject(error);
            })
            .pipe(csv({headers: false, separator: ';',}))
            .on('data', (row) => {
                let item = {
                    date: row[0],
                    value: row[1]
                };
                let item2 = {
                    date: moment(row[0], "DD-MM-YYYY HH:mm").add(30, "minutes").format("DD/MM/YYYY HH:mm"),
                    value: row[2]
                };
                data.push(item);
                data.push(item2);
            })
            .on('end', () => {
                resolve(data);
            });
    });
}

async function testGetData() {
    try { 
        const data = await getData("test.csv", {});
        console.log("testGetData: parsed CSV data:", data);
    } catch (error) {
        console.error("testGetData: An error occurred: ", error.message);
    }
}

testGetData();
Sign up to request clarification or add additional context in comments.

1 Comment

niiiiiice! way to go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.