【问题标题】:How to pass value from serverless yml file to js file?如何将值从无服务器 yml 文件传递​​到 js 文件?
【发布时间】:2021-08-28 06:31:21
【问题描述】:
serverless.yml file    
provider:
      name: aws
      runtime: nodejs12.x
      memorySize: 512
      stage: ${opt:stage, 'test'}
      timeout: 30
    ##
    ##...
    custom:
      getValue: ${file(key.js):randomVal} //pass the string from here


key.js file
module.exports.randomVal = async (context) => {
    #code //get the string here
    console.log(context.providers);
};

在上面的代码中,我从无服务器 yml 文件中调用 randomVal() 函数,我想从 yml 文件中将字符串传递给该函数。 有什么方法可以实现吗?

【问题讨论】:

    标签: javascript yaml amazon-cloudformation serverless-framework


    【解决方案1】:

    我查看了无服务器文档,但似乎没有正式的方法可以做到这一点。

    但是,作为一种解决方法,您可以使用像 https://www.npmjs.com/package/yaml 这样的 npm 包来解析 key.js 文件中的 serverless.yml 文件

    然后做这样的事情:

    custom:
      getValue:
        fn: ${file(key.js):randomVal}
        params: 
          someVar: foo
          someOtherVar: bar
    

    当您在 key.js 中解析 serverless.yml 时,您可以只使用普通的 not notation 来获取参数:

    const YAML = require('yaml')
    const fs = require('fs')
    
    const file = fs.readFileSync('./serverless.yml', 'utf8')
    const parsedYaml = YAML.parse(file)
    
    module.exports.randomVal = () => {
        let myVar = parsedYaml.custom.getValue.params.someVar
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      相关资源
      最近更新 更多