@adonisjs/env

中文文档
7.1.0发布于 2026/09/04MITTypeScriptES Module构建来源已验证近 30 天下载 78.8万

Environment variable manager for Node.js

原始使用文档
文档目录9 节
  1. Setup
  2. EnvLoader
  3. EnvParser
  4. Identifier
  5. Validating environment variables
  6. Complete example
  7. Env editor
  8. Known Exceptions
  9. E_INVALID_ENV_VARIABLES

@adonisjs/env

Environment variables parser and validator used by the AdonisJS.

gh-workflow-image typescript-image npm-image license-image

Note: This package is framework agnostic and can also be used outside of AdonisJS.

The @adonisjs/env package encapsulates the workflow around loading, parsing, and validating environment variables.

Setup

Install the package from the npm packages registry as follows.

npm i @adonisjs/env

EnvLoader

The EnvLoader class is responsible for loading the environment variable files from the disk and returning their contents as a string.

import { EnvLoader } from '@adonisjs/env'

const lookupPath = new URL('./', import.meta.url)
const loader = new EnvLoader(lookupPath)

const envPaths = loader.getPaths()
const envFiles = await loader.load()

getPaths returns the absolute paths of every dot-env file the loader may load, in priority order. It includes files that do not exist and does not read from the filesystem.

The load return value is an array of objects with following properties.

  • path: The path to the loaded dot-env file.
  • contents: The contents of the file.

Following is the list of loaded files. The array is ordered by the priority of the files. The first file has the highest priority and must override the variables from the last file.

PriorityFile nameEnvironmentShould I .gitignore itNotes
1st.env.[NODE_ENV].localCurrent environmentYesLoaded when NODE_ENV is set
2nd.env.localAllYesLoaded in all the environments except test or testing environments
3rd.env.[NODE_ENV]Current environmentNoLoaded when NODE_ENV is set
4th.envAllDependsLoaded in all the environments. You should .gitignore it when storing secrets in this file
5th.env.exampleAllNoLoaded when loadExampleFile is enabled

EnvParser

The EnvParser class is responsible for parsing the contents of the .env file(s) and converting them into an object.

import { EnvParser } from '@adonisjs/env'
const envParser = new EnvParser(`
  PORT=3000
  HOST=localhost
`)

console.log(await envParser.parse()) // { PORT: '3000', HOST: 'localhost' }

The return value of parser.parse is an object with key-value pair. The parser also has support for interpolation.

By default, the parser prefers existing process.env values when they exist. However, you can instruct the parser to ignore existing process.env files as follows.

new EnvParser(envContents, { ignoreProcessEnv: true })

Identifier

You can define an "identifier" to be used for interpolation. The identifier is a string that prefix the environment variable value and let you customize the value resolution.

import { readFile } from 'node:fs/promises'
import { EnvParser } from '@adonisjs/env'

EnvParser.identifier('file', (value) => {
  return readFile(value, 'utf-8')
})

const envParser = new EnvParser(`
  DB_PASSWORD=file:/run/secret/db_password
`)

console.log(await envParser.parse()) // { DB_PASSWORD: 'Value from file /run/secret/db_password' }

This can be useful when you are using secrets manager like Docker Secret, HashiCorp Vault, Google Secrets Manager and others to manage your secrets.

Validating environment variables

Once you have the parsed objects, you can optionally validate them against a pre-defined schema. We recommend validation for the following reasons.

  • Fail early if one or more environment variables are missing.
  • Cast values to specific data types.
  • Have type safety alongside runtime safety.
import { Env } from '@adonisjs/env'

const validator = Env.rules({
  PORT: Env.schema.number(),
  HOST: Env.schema.string({ format: 'host' })
})

The Env.schema is a reference to the @poppinss/validator-lite schema object. Make sure to go through the package README to view all the available methods and options.

The Env.rules method returns an instance of the validator to validate the environment variables. The return value is the validated object with type information inferred from the schema.

validator.validate(process.env)

Complete example

Following is a complete example of loading dot-env files and validating them in one go.

Note: Existing process.env variables have the top most priority over the variables defined in any of the files.

import { Env } from '@adonisjs/env'

const env = await Env.create(new URL('./', import.meta.url), {
  PORT: Env.schema.number(),
  HOST: Env.schema.string({ format: 'host' })
})

env.get('PORT') // is a number
env.get('HOST') // is a string
env.get('NODE_ENV') // is unknown, hence a string or undefined

Env editor

The Env editor can be used to edit dot-env files and persist changes on disk. Only the .env and .env.example files are updated (if exists).

import { EnvEditor } from '@adonisjs/env/editor'

const editor = await EnvEditor.create(new URL('./', import.meta.url))
editor.add('PORT', 3000)
editor.add('HOST', 'localhost')

// Write changes on disk
await editor.save()

You can also insert an empty value for the .env.example file by setting the last argument to true.

editor.add('SECRET_VARIABLE', 'secret-value', true)

This will add the following line to the .env.example file.

SECRET_VARIABLE=

Known Exceptions

E_INVALID_ENV_VARIABLES

The exception is raised during environment variables validation exception. The exception is raised with Validation failed for one or more environment variables message.

You can access the detailed error messages using the error.cause property.

try {
  validate(envValues)
} catch (error) {
  console.log(error.cause)
}

版本与发布记录

@adonisjs/env 共发布 66 个版本,首次发布于 2019/09/05;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
7.1.0latest2026/09/042 个月前
7.0.02026/02/258 个月前
7.0.0-next.3next2025/12/1510 个月前
7.0.0-next.22025/09/081.2 年前
7.0.0-next.12025/08/281.2 年前
7.0.0-next.02025/08/151.2 年前

关于 @adonisjs/env 的常见问题

@adonisjs/env 是什么?

Environment variable manager for Node.js

如何安装 @adonisjs/env?

在项目目录运行 npm install @adonisjs/env,或使用 pnpm add / yarn add / bun add。

@adonisjs/env 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adonisjs/env 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adonisjs/env 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adonisjs/env 可以商用吗?

@adonisjs/env 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@adonisjs/env 的下载量有多少?

根据 npm 官方下载统计,@adonisjs/env 在 2026/10/05 – 2026/11/03 这 30 天内被下载 787,911 次,日均约 26,264 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adonisjs/env 还在维护吗?

最新版本 7.1.0 发布于 2026/09/04(2 个月前);至今共发布 66 个版本,其中过去 12 个月发布了 3 个;首次发布于 2019/09/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。