使用nodejs AWS lambda从S3加载并解析yaml文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用nodejs AWS lambda从S3加载并解析yaml文件相关的知识,希望对你有一定的参考价值。

我有一个AWS lambda,必须......

  • 从S3读取一个yaml文件,
  • 将内容转换为对象,
  • 有一些很棒的工作人员。

我可以处理最后一点,但我不知道如何读取和解析该yaml文件。

这是我需要完成的代码:

const AWS = require('aws-sdk');
const YAML = require('js-yaml');

const S3 = new AWS.S3();

module.exports.handler = (event, context, callback) => {
  const [record] = event.Records;
  const bucket = record.s3.bucket.name;
  const { key } = record.s3.object;

  const params = { Bucket: bucket, Key: key };
  console.log(params);

  S3.getObject(params).promise()
    .then((x) => {

      // ?????????????????????????????????????????
      // HOW TO DO SOME MAGIC AND GET THE OBJECT ?

    })
    .then((fileContentObject) => {
      // DO SOME WONDERFUL STAFF (example: console.log :) )
      console.log(JSON.stringify(fileContentObject))
    })
    .then(() => callback)
    .catch(callback);
};

随意建议另一种方法来读取和解析yaml文件。如果可能的话,我更喜欢Promise方法。

答案

我终于解决了这个问题。 “很容易”,当然!

这是lambda中的代码:

S3.getObject(params).promise()
  .then((configYaml) => {
    // Get the content of the file as a string
    // It works on any text file, should your config is in another format
    const data = configYaml.Body.toString('utf-8');
    console.log(data);

    // Parse the string, which is a yaml in this case
    // Please note that `YAML.parse()` is deprecated
    return YAML.load(data);
  })
  .then((config) => {
    // Do some wonderful staff with the config object
    console.log(`• Config: ${JSON.stringify(config)}`);
    return null;
  })
  .then(callback)
  .catch(callback);

我所要求的只是:YAML.load(configYaml.Body.toString('utf-8'))

以上是关于使用nodejs AWS lambda从S3加载并解析yaml文件的主要内容,如果未能解决你的问题,请参考以下文章