0

I am trying to get the data from a csv-file as a json-object on my server:

const express = require('express');
const router = express.Router();
const csv = require('csvtojson');
const converter = csv({
    noheader: true,
    delimiter: ',',
    headers: ['date', 'time', 'point1', 'point2', 'point3', 'point4', 'point5']
});

router.get('/get-sample', (req, res) => { 
    converter.fromFile('./file.csv').then((jsonObj) => {
        res.send(jsonObj);
    });
});

Now the first time I send a request everything works fine but when sending more requests I get this error:

Unhandled rejection Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at _write (node:internal/streams/writable:319:11)
at Converter.Writable.write (node:internal/streams/writable:334:10)
at ReadStream.ondata (node:internal/streams/readable:754:22)
at ReadStream.emit (node:events:394:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at ReadStream.Readable.push (node:internal/streams/readable:228:10)
at node:internal/fs/streams:273:14
at FSReqCallback.wrapper [as oncomplete] (node:fs:660:5)

If I use csv().fromFile instead it works but I need the options set in the converter. How can I fix that?

2 Answers2

0

It's not that clean but it works:

router.get('/get-sample', (req, res) => { 
    csv({
        noheader: true,
        delimiter: ',',
        headers: ['date', 'time', 'point1', 'point2', 'point3', 'point4', 'point5']
    }).fromFile('./file.csv').then((jsonObj) => {
       res.send(jsonObj);
    });
});
0

The problem here is that you are re-using the converter. It works for the first request but not for any subsequent requests - see below for an example which will work for multiple requests:

const express = require('express');
const router = express.Router();
const csv = require('csvtojson');    

router.get('/get-sample', (req, res) => {
    const converter = csv({
       noheader: true,
       delimiter: ',',
       headers: ['date', 'time', 'point1', 'point2', 'point3', 'point4', 'point5']
    });
    converter.fromFile('./file.csv').then((jsonObj) => {
        res.send(jsonObj);
    });
});
Ron
  • 129
  • 2
  • 8