gpt4 book ai didi

使用 Nestjs 和 Papa Parse 处理 CSV 文件

转载 作者:行者123 更新时间:2023-12-03 08:01:40 24 4
gpt4 key购买 nike

我正在尝试使用 Multer 和 Papa Parse 在 NestJS 中处理 CSV 文件。我不想将文件存储在本地。我只想解析 CSV 文件以提取一些信息。

但是我无法处理它,我尝试了两种不同的方法。在第一个中,我将文件缓冲区传递给 Papa.parse 函数。但是,我收到错误:ReferenceError:FileReaderSync 未定义

@Post('1')
@UseInterceptors(
FileInterceptor('file', {})
)
async uploadFile(@UploadedFile() file: Express.Multer.File ){
const csvData = papa.parse(file.buffer, {
header: false,
worker: true,
delimiter: ",",
step: function (row){
console.log("Row: ", row.data);
}
});
}

因此尝试调用 readFileSync() 如下所示,但是这次我收到错误,ERROR [ExceptionsHandler] ENAMETOOLONG: name too long, open

@Post('2')
@UseInterceptors(
FileInterceptor('file', {})
)
async uploadFile(@UploadedFile() file: Express.Multer.File ){
const $file = readFileSync(file.buffer);
const csvData = papa.parse($file, {
header: false,
worker: true,
delimiter: ",",
step: function (row){
console.log("Row: ", row.data);
}
});
}

非常感谢您为解决此问题提供的任何帮助。

最佳答案

正如@skink所指出的,文件缓冲区需要先转换为流,然后才能被papa解析使用。

const { Readable } = require('stream');

并更新了函数,在调用parse()之前将 file.buffer 转换为流

@Post('1')
@UseInterceptors(
FileInterceptor('file', {})
)
async uploadFile(@UploadedFile() file: Express.Multer.File ){
const stream = Readable.from(file.buffer);
const csvData = papa.parse(stream, {
header: false,
worker: true,
delimiter: ",",
step: function (row){
console.log("Row: ", row.data);
}
});
}

关于使用 Nestjs 和 Papa Parse 处理 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73867031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com