【问题标题】:Store and access data files in lambda function在 lambda 函数中存储和访问数据文件
【发布时间】:2020-12-29 18:43:10
【问题描述】:

如何将自定义文件(在我的情况下为 .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
  });
});

【问题讨论】:

  • 为什么要将 json 文件存储在可以存储在 S3 存储桶中并直接在 lambda 中访问的层内。

标签: aws-lambda


【解决方案1】:

这是您在 Lambda 函数中使用存储数据文件所需的内容。创建一个名为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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 2017-06-06
    • 2021-07-16
    • 2020-12-05
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多