Aws lambda 在lambda函数中存储和访问数据文件
如何将自定义文件(.json)存储在lambda层中,以便像npm模块一样访问它?我使用node.js作为运行时。我当前的图层文件夹结构如下所示: 存储在Aws lambda 在lambda函数中存储和访问数据文件,aws-lambda,Aws Lambda,如何将自定义文件(.json)存储在lambda层中,以便像npm模块一样访问它?我使用node.js作为运行时。我当前的图层文件夹结构如下所示: 存储在node\u modules中的我的模块可见,可以通过以下方式访问: const { Client } = require('pg'); const knex = require('knex'); 但当我尝试列出可用文件时,我看不到我的服务帐户文件.json文件: fs.readdir('./', (err, files) => {
node\u modules
中的我的模块可见,可以通过以下方式访问:
const { Client } = require('pg');
const knex = require('knex');
但当我尝试列出可用文件时,我看不到我的服务帐户文件.json
文件:
fs.readdir('./', (err, files) => {
files.forEach(file => {
console.log('@file')
console.log(file); // Returns only index.js
});
});
以下是在Lambda函数中使用存储的数据文件所需的内容。创建一个名为
data\u files
的文件夹,将您的服务帐户文件.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');
以下是在Lambda函数中使用存储的数据文件所需的内容。创建一个名为
data\u files
的文件夹,将您的服务帐户文件.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');
为什么要在层内存储json文件,可以将其存储在S3 bucket中并直接在lambda中访问。为什么要在层内存储json文件,可以将其存储在S3 bucket中并直接在lambda中访问。