使用NestJS与Papa Parse处理CSV文件遇错求助
在NestJS中用Multer + Papa Parse解析CSV(无本地存储)
错误原因分析
第一个错误(FileReaderSync is not defined)
worker: true是Papa Parse为浏览器环境设计的多线程解析选项,Node.js运行时不存在FileReaderSyncAPI,开启该选项必然触发报错。第二个错误(ENAMETOOLONG)
fs.readFileSync()要求传入文件路径字符串,你直接传入了文件buffer,Node会把整个buffer内容当作文件名处理,自然触发文件名过长的错误。
正确解决方案
关闭worker模式,直接使用Multer提供的文件buffer解析即可。Papa Parse支持直接传入buffer或转换后的字符串:
import { Controller, Post, UploadedFile } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import * as papa from 'papaparse'; @Controller('csv') export class CsvController { @Post('upload') @UseInterceptors(FileInterceptor('file')) async uploadFile(@UploadedFile() file: Express.Multer.File) { papa.parse(file.buffer, { header: false, worker: false, // 必须关闭worker模式 delimiter: ',', step: (row) => { console.log('Row:', row.data); }, complete: () => { console.log('CSV解析完成'); }, }); } }
大文件优化方案
如果需要处理超大CSV文件,推荐使用流式解析避免内存溢出,利用Node.js的stream结合Papa Parse的NODE_STREAM_INPUT模式:
import { PassThrough } from 'stream'; // ... @Post('upload-stream') @UseInterceptors(FileInterceptor('file')) async uploadFileStream(@UploadedFile() file: Express.Multer.File) { const stream = new PassThrough(); stream.end(file.buffer); papa.parse(papa.NODE_STREAM_INPUT, { input: stream, header: false, delimiter: ',', step: (row) => { console.log('Row:', row.data); }, complete: () => { console.log('流式解析完成'); }, }); }
内容的提问来源于stack exchange,提问作者Adnan Mian
相关产品推荐
相关产品推荐

