0

I am using csv-parser to parse a csv I have gotten from a POST request. The problem is, that after I restart the nodeserver, It only manages to parse the first csv from the first submission of the POST form, not any of the next ones. I am moving the file from the request to a temporary location right before i try to parse it, in case that makes a difference.

the following code is executed after a POST reqest has been recieved.

    let fil = req.files['csv'];

    let filePath = path.join(__dirname, '../filer/tmp.csv');

    await fil.mv(filePath, (err) => {
        if(err) {
            console.log("move_err: " + err)
        }
    })

    await fs.createReadStream(filePath)
        .pipe(csv({separator: ';'}))
        .on('data', (data) => console.log(data))
        .on('end', () => console.log('done'))
        .on('error', (err) => console.log(err));

Any help is appriciated

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • _"It only manages to parse the first csv from the first submission"_. So what exactly happens after that first request? – robertklep Aug 22 '22 at 17:21
  • @robertklep It sends a response to go to the same page that the client is already on, essentially refreshing the page. Nothing special really happens after the first request is parsed – Leif Magnus Gauksås Aug 23 '22 at 10:26
  • @robertklep When the csv file is submitted through the form a second time, all that is logged is "done" – Leif Magnus Gauksås Aug 23 '22 at 10:35
  • It might be because you're mixing promises with callbacks in the call to `fil.mv()`. Stick to using promises. – robertklep Aug 23 '22 at 10:44
  • @robertklep What does that mean? – Leif Magnus Gauksås Aug 23 '22 at 10:51
  • You're passing a callback to `fil.mv()` to handle errors, but also using `await`. _Don't_ pass the callback and use `try/catch` to handle errors. – robertklep Aug 23 '22 at 10:53
  • @robertklep I tried this instead now, and it seems to work: ```fil.mv(filePath).then(function(){ fs.createReadStream(filePath) .pipe(csv({separator: ';'})) .on('data', (data) => console.log(data)) .on('end', () => console.log('done')) .on('error', (err) => console.log(err)); }, function(){ console.log('error') })``` – Leif Magnus Gauksås Aug 23 '22 at 11:01
  • That's basically the same as what I suggested. – robertklep Aug 23 '22 at 11:08

0 Answers0