在AWS Lambda TypeScript处理程序中无法使用fileTypeFromStream方法
问题原因及解决办法
环境信息
- Node.js版本:v20.17.0
- 依赖包版本:
- @types/aws-lambda^8.10.145
- @aws-sdk/client-s3^3.678.0
- file-type^19.6.0
问题原因
- 类型不兼容:AWS SDK v3的
GetObjectCommand返回的是Node.js原生Readable流,但file-type@19.x的fileTypeFromStream要求传入Web Streams API标准的ReadableStream,直接传递会触发TypeScript编译错误。 - 运行时错误根源:调用
transformToWebStream转换后的Web Stream不支持BYOB(后台日志显示supportsBYOB: false),而file-type内部依赖BYOBReader读取流数据,不符合要求的流会抛出参数无效错误。
解决办法
办法一:将Node流转换为支持BYOB的Web Stream
Node.js v20+原生支持stream/web模块的Readable.toWeb()方法,转换后的Web Stream默认支持BYOB,完全符合fileTypeFromStream的要求:
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { fileTypeFromStream } from "file-type"; import { Readable } from 'stream/web'; const s3Client = new S3Client({ region: 'your-region' }); export const handler = async (event) => { const command = new GetObjectCommand({ Bucket: 'your-bucket', Key: 'your-object-key' }); const response = await s3Client.send(command); // 转换为支持BYOB的Web ReadableStream const webStream = Readable.toWeb(response.Body); const fileType = await fileTypeFromStream(webStream); console.log('文件类型:', fileType); return { statusCode: 200, body: JSON.stringify(fileType) }; };
办法二:转换为Buffer后使用fileTypeFromBuffer
如果不需要流式处理,可将S3流数据收集为Buffer,改用file-type的fileTypeFromBuffer方法,彻底规避流类型兼容问题:
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { fileTypeFromBuffer } from "file-type"; import { pipeline } from "stream/promises"; import { Buffer } from "buffer"; const s3Client = new S3Client({ region: 'your-region' }); export const handler = async (event) => { const command = new GetObjectCommand({ Bucket: 'your-bucket', Key: 'your-object-key' }); const response = await s3Client.send(command); const chunks = []; // 收集流数据到Buffer await pipeline(response.Body, { write(chunk) { chunks.push(chunk); } }); const buffer = Buffer.concat(chunks); const fileType = await fileTypeFromBuffer(buffer); console.log('文件类型:', fileType); return { statusCode: 200, body: JSON.stringify(fileType) }; };
内容的提问来源于stack exchange,提问作者bssyy78
相关产品推荐
相关产品推荐

