AWS Lambda无法写入tmp目录并向Webhook发送文件求助
AWS Lambda写入临时文件失败问题排查与解决
问题描述
在AWS Lambda实例中写入/tmp文件夹时遇到异常,本地通过serverless offline测试发送文件正常,但部署到AWS后三种路径均失效。
相关代码
const fs = require('fs-extra'); const os = require('os'); const cwd = process.cwd(); const buffer = Buffer.from(arrayBuffer, 'base64'); const newFileName = 'myFile.png'; const temporaryImageDirectory = os.tmpdir(); // filePath本地可用,但部署到Lambda后无效,CloudWatch无错误 const filePath = `/tmp/${newFileName}`; // 本地可用 // filePath1本地可用,但部署到Lambda后无效,CloudWatch无错误 const filePath1 = `${cwd}/${newFileName}`; // 本地可用 // filePath2本地可用,但部署到Lambda后无效,CloudWatch报错:EROFS: read-only file system, open '/var/task/myFile.png' const filePath2 = `${temporaryImageDirectory}/${newFileName}`; // 本地可用 console.log('FILE PATH: ', filePath); console.log('FILE PATH1: ', filePath1); console.log('FILE PATH2: ', filePath2); fs.writeFile(filePath, buffer, 'utf-8') .then(() => { webhook.sendFile(filePath); }) .catch((e) => { console.log('Error', e); });
CloudWatch错误信息
CloudWatch打印显示filePath2实际指向/var/task/myFile.png,完整错误如下:
Error [Error: EROFS: read-only file system, open '/var/task/myFile.png'] { errno: -30, code: 'EROFS', syscall: 'open', path: '/var/task/myFile.png' }
解决方案
1. 固定使用Lambda可写临时路径
Lambda唯一的可写临时目录是/tmp,直接硬编码该路径比依赖os.tmpdir()更可靠——部分旧版Node.js运行时在Lambda环境中os.tmpdir()会错误返回只读的/var/task路径。
2. 修复图片Buffer写入的编码错误
你当前用utf-8编码写入图片Buffer,会导致文件损坏,应去掉编码参数,直接写入原始Buffer:
// 正确写入方式:不指定utf-8编码 fs.writeFile(`/tmp/${newFileName}`, buffer) .then(() => webhook.sendFile(`/tmp/${newFileName}`)) .catch((e) => console.log('Error', e));
3. 补充文件存在性校验(可选)
为确保文件写入成功后再执行发送操作,可增加存在性检查:
fs.writeFile(`/tmp/${newFileName}`, buffer) .then(() => fs.pathExists(`/tmp/${newFileName}`)) .then((exists) => { if (exists) { return webhook.sendFile(`/tmp/${newFileName}`); } throw new Error('临时文件创建失败'); }) .catch((e) => console.log('Error', e));
4. 明确路径不可用原因
process.cwd()在Lambda中指向/var/task,该目录是只读的,因此filePath1必然无法写入;- 若
os.tmpdir()返回错误路径,建议升级Node.js运行时到14.x及以上版本,该版本在Lambda中可正确返回/tmp。
内容的提问来源于stack exchange,提问作者user6680
相关产品推荐
相关产品推荐

