0

我正在尝试从 csv 文件中获取数据作为服务器上的 json 对象:

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);
    });
});

现在我第一次发送请求时一切正常,但是当发送更多请求时出现此错误:

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)

如果我使用 csv().fromFile 代替它可以工作,但我需要在转换器中设置选项。我该如何解决?

4

1 回答 1

0

它不是那么干净,但它有效:

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);
    });
});
于 2021-09-16T13:49:33.607 回答