aws-lambda - 在 lambda 函数中存储和访问数据文件
问题描述
如何将自定义文件(在我的情况下为 .json)存储在 lambda 层中,以便我可以像 npm 模块一样访问它?我使用 node.js 作为运行时。我当前的图层文件夹结构如下所示:
我存储的模块node_modules
是可见的,可以通过以下方式访问:
const { Client } = require('pg');
const knex = require('knex');
但是当我尝试列出可用文件时,我看不到我的service-account-file.json
文件:
fs.readdir('./', (err, files) => {
files.forEach(file => {
console.log('@file')
console.log(file); // Returns only index.js
});
});
解决方案
这是您在 Lambda 函数中使用存储数据文件所需的内容。用 name 创建一个文件夹data_files
,把你的service-account-file.json
文件放在那里。
const path = require('path');
const fs = require("fs");
const loadDataFile = (file) => {
//create the filename including path
const fileName = `./data_files/${file}`;
//set up the variable
let resolved;
//if we have a lambda environment then add that to the path to resolve
if (process.env.LAMBDA_TASK_ROOT) {
//this creates an absolute path
resolved = path.resolve(process.env.LAMBDA_TASK_ROOT, fileName);
} else {
//otherwise resolve to the local path
resolved = path.resolve(__dirname, fileName);
}
try {
//get the text data as a string
let data = fs.readFileSync(resolved, 'utf8');
//convert to JS object
let parsedData = JSON.parse(data);
//TO DO - work data if required
//then return the data
return parsedData;
} catch (error) {
//if there'a an error in the data fetch then we need a report
console.log(error.message);
}
};
const data = loadDataFile('service-account-file.json');
推荐阅读
- sql-server - Visual Studio SQL Server 数据比较“当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'MyTable' 中插入标识列的显式值”
- excel - 将工作簿中的所有 Excel 选项卡合并到另一个工作簿上的最小选项卡中
- visual-studio-code - 在 VSCode 中格式化注释块
- python - 文本分类 - 处理不属于任何类别的文本
- c++ - 来自 C++ QAbstractListModel 的 Qml ListView 与 QThread 处理
- android - 如何在 Activity 之外使用 Image Uri?
- javascript - svg 可以在直接添加到 dom 时显示,但不能在其 base64 转换字符串作为 img 源传递时显示
- sql - SQL 正则表达式替换多个条件
- airflow - Airflow 2.0 - 重复键值违反唯一约束“ab_view_menu_name_key”..键(名称)=(DAG:xxx)已经存在
- jquery - JQuery Toggle show hide