我正在尝试使用 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/