首页 > 解决方案 > 在 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
  });
});

标签: aws-lambda

解决方案


这是您在 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');

推荐阅读