在 AWS Lambda 调用本地文件夹时,需要根据实际情况进行适当的内存管理,以避免内存泄漏问题。
以下是一个可能导致内存泄漏的示例代码:
exports.handler = async (event, context, callback) => {
const fs = require('fs');
const contents = fs.readFileSync('/path/to/local/folder');
// do something with contents
callback(null, 'Success');
};
上述代码中的 fs.readFileSync
方法会将整个文件内容读取到内存中,如果文件非常大,就会导致内存泄漏。为了避免这种情况,可以使用 node.js 的 stream API,以逐行读取或逐块读取文件数据:
exports.handler = async (event, context, callback) => {
const fs = require('fs');
const stream = fs.createReadStream('/path/to/local/folder');
stream.on('data', function(chunk) {
// do something with chunk
});
stream.on('end', function() {
callback(null, 'Success');
});
};
上述代码中的 fs.createReadStream
方法会将文件内容分块读取,避免一次性读取整个文件导致的内存泄漏问题。