【问题标题】:CSV File Processing with Nestjs and Papa Parse使用 Nestjs 和 Papa Parse 处理 CSV 文件
【发布时间】:2022-09-27 20:41:12
【问题描述】:

我正在尝试使用 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() 如下所示,但这次我得到了错误,错误 [ExceptionsHandler] ENAMETOOLONG:名称太长,打开

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

将不胜感激解决此问题的任何帮助。

标签: csv file-upload nestjs papaparse file-processing


【解决方案1】:

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

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

并更新了函数,在调用之前将 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);
        }
      });
}

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多