我正在尝试使用以字符串形式提供的代码(而不是本地文件)更新 AWS Lambda 函数。我使用 v3 sdk 库
client.updateFunctionCode({
FunctionName: "myFunc",
ZipFile: Buffer.from("console.log('hey')", "base64")
})
但是我收到错误:
无法解压缩上传的文件。请检查您的文件,然后尝试 重新上传。
官方文档:
如果函数的包类型是Zip,则必须指定 作为 .zip 文件存档的部署包。输入 Amazon S3 存储桶 以及代码 .zip 文件位置的键。 您还可以提供 使用 ZipFile 字段内联函数代码。
我是否误解了文档或者 AWS SDK 不支持此功能?
这是 Python CDK 中的示例 -
lambda_.Function(stack, "MyLayeredLambda",
code=lambda_.InlineCode("foo"),
handler="index.handler",
runtime=lambda_.Runtime.NODEJS_LATEST,
layers=[layer]
)
我发现了解决方案。事实证明,我需要做的就是创建一个能够将所有文件及其内容压缩到内存中的函数,然后传递该缓冲区字符串。
import archiver from 'archiver';
import { Writable } from 'stream';
// Define a type for the objects in the files array
export type FileContent = {
name: string;
content: string;
};
export function zipFiles(files: FileContent[]): Promise<Buffer> {
return new Promise((resolve, reject) => {
const buffs: Buffer[] = [];
const converter = new Writable({
write(chunk, encoding, callback) {
buffs.push(chunk as Buffer); // Assure TypeScript that `chunk` is a Buffer
process.nextTick(callback);
},
});
converter.on('finish', () => {
resolve(Buffer.concat(buffs));
});
const archive = archiver('zip', {
zlib: { level: 9 }, // Compression level
});
archive.on('error', (err: Error) => {
reject(err);
});
archive.pipe(converter);
files.forEach((file) => {
archive.append(Buffer.from(file.content), { name: file.name });
});
archive.finalize();
})
}
最后,这条线有效:
client.updateFunctionCode({
FunctionName: "my-func",
ZipFile: zip
})