使用fast-csv处理CSV后流式上传S3遇类型错误如何解决?
解决fast-csv流式处理后上传S3的「ERR_INVALID_ARG_TYPE」错误
错误原因
你的代码中,csv.parse()解析CSV后输出的是JavaScript对象,直接将这个对象流pipe到PassThrough再传给S3 Upload时,S3要求Body必须是字符串、Buffer或Uint8Array类型,因此抛出类型错误。本质是缺少了「将转换后的对象重新序列化为CSV格式文本」的步骤。
修复方案
在transform之后添加csv.format()流,把转换后的JS对象重新编码为CSV格式的文本流,这样后续传递给S3的就是符合要求的字节数据。
修改后的完整代码
const { S3Client, GetObjectCommand, Upload } = require("@aws-sdk/client-s3"); const { PassThrough } = require("stream"); const csv = require("fast-csv"); const s3Client = new S3Client({ region: 'eu-west-2' }); const getFileFromS3 = async () => { const command = new GetObjectCommand({ Bucket: 'mybucket', Key: 'originaldata.csv', }); const getFile = await s3Client.send(command); return getFile.Body; // S3返回的Body本身就是流,无需await }; // 修正:添加csv.format()将转换后的对象序列化为CSV文本 const csvProcessingStream = csv .parse({ headers: true }) .transform((data) => ({ ...data, id: 'TEST', })) .pipe(csv.format({ headers: true })) // 新增:将对象转为CSV格式 .on('error', (error) => console.error(error)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); const run = async () => { const fileStream = await getFileFromS3(); const transformationStream = new PassThrough(); fileStream.pipe(csvProcessingStream).pipe(transformationStream); const upload = new Upload({ client: s3Client, params: { Bucket: 'mybucket', Key: 'processeddata.csv', Body: transformationStream, }, }); await upload.done(); console.log('文件上传完成'); }; run().catch(console.error);
关键修改点
- 新增
csv.format({ headers: true })流,衔接在transform之后,负责将JS对象转换回CSV格式的文本 - 调整了流的命名,让逻辑更清晰
- 修正了
getFileFromS3中对getFile.Body的多余await(S3返回的Body本身就是ReadableStream,无需await)
内容的提问来源于stack exchange,提问作者ProEvilz
相关产品推荐
相关产品推荐

