0

I'm creating a small tool for internal user with puppeteer.

Basically I got a csv file with some data i "read" and fill form with.

As I try to cleanup my project to be reusable i'm struggle a little bit:

I create a file name parsecsv.js

const config = require('../config.json');
const parse = require('csv-parse');
const fs = require('fs');

const processFile = async () => {
    records = []
    const parser = fs
        .createReadStream(config.sourceFile)
        .pipe(parse({
            // CSV options
            from_line: 1,
            delimiter: ";",
        }));
    let i =1;
    for await (const record of parser) {
        records.push(record)
        i++;
    }
    return records
}

const processFileData = async () => {
    const records = await processFile()
    console.info(records);
    return records
}


module.exports ={
    processFile, processFileData
}

in an other Js file i made

const parseCSV = require('./src/ParseCsv');
const records = parseCSV.processFileData();
const data = parseCSV.processFile();
console.log(typeof records);
console.table(records);
console.log(typeof data);
console.table(data);

But I never get my data only an empty oject. How I can get my data to be able to "share" it with other function ?

thanks

Mitchum
  • 107
  • 2
  • 16

1 Answers1

0

as your functions are async ones and they return a promises, you can do something like

const parseCSV = require('./src/ParseCsv');
(async () => {
        const records = await parseCSV.processFileData();
        const data = await parseCSV.processFile();
        console.log(typeof records);
        console.table(records);
        console.log(typeof data);
        console.table(data);
         
          })()
Youba
  • 2,636
  • 3
  • 11
  • 25
  • thanks for the hint ! I ended up doing this : ```async function getData() { const records = await parseCSV.processFile(); return records; } const data = getData(); data.then(function(result) { console.table(result); }) ``` and working like a charm :) – Mitchum Jan 08 '21 at 12:36
  • you're right ! your solution work (as first not working but from a typo on my side...) Both work, but will keep your as "shorter" :) – Mitchum Jan 08 '21 at 13:10