简体   繁体   English

使用 JOI 获取环境变量

[英]Get Environment Variable with JOI

I'm using joi to structure data.我正在使用joi来构造数据。
Now I'm unable to read environment variable set on startup.现在我无法读取启动时设置的环境变量。

I have a startup scrip.sh like:我有一个启动 scrip.sh,例如:

PUBLIC_KEY="$(cat public_key.pem) docker-compose up --build"

Then I try to read that PUBLIC_KEY variable.然后我尝试读取那个PUBLIC_KEY变量。

const envVariables = joi.object({
 PUBLIC_KEY: joi.string()
    .default('PUBLIC_KEY')
})

I thought this would automatically identify the variable but it does not.我认为这会自动识别变量,但事实并非如此。
Is it possible to get the variable set on start up with Joi?是否可以在使用 Joi 启动时设置变量?

You can get environment variables using the process core module.您可以使用process核心模块获取环境变量。 From the documentation :文档中:

The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started. Node.js 的进程核心模块提供了 env 属性,该属性托管在进程启动时设置的所有环境变量。

For example,例如,

const pubKey = process.env.PUBLIC_KEY
  1. Joi does not provide variables, at least in such a way you want Joi提供变量,至少以您想要的方式
  2. use it from the process if it's provided by CLI arguments or additionally use dotenv.config() to read synchronously from .env files如果它由 CLI arguments 提供,则从process使用它,或者另外使用dotenv.config().env文件中同步读取
  3. if you need to read some previous value inside Joi schema logic you eg for some conditions you cat try this example如果您需要在 Joi 模式逻辑中读取一些先前的值,例如对于某些条件,您可以尝试这个示例
var schema = {
    a: Joi.string(),
    b: Joi.string(),
    c: Joi.string().when('a', { is: 'avalue', then: Joi.string().required() }).concat(Joi.string().when('b', { is: 'bvalue', then: Joi.string().required() }))
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM