Convert YAML configuration into dotenv-style text: one KEY=value per line (newline-terminated), ready for .env files, Docker, Kubernetes, CI, and anything that reads that format.
Under the hood, valid YAML is parsed to a plain object, serialized to JSON, and passed to @sourcepride/json-to-env jsonToEnv. All flattening, array/object modes, key casing, and prefix behavior come from that library.
- YAML in,
.envlines out — nested mappings become flattened keys by default (db.host→DB_HOST=…). - Same
OptionsasjsonToEnv—arrays,objects,keyCase,prefix,separator(TypeScript type re-exported from this package). - Dual module formats — CommonJS (
require) and ESM (import) builds, plus TypeScript declarations. - CLI — read a YAML file, print dotenv lines to stdout, or pass a second path to write a
.envfile. - Strict about document shape — the YAML root must be a mapping (key/value object), not a bare scalar, sequence-only document, or empty document.
- Node.js ≥ 14 (see
enginesinpackage.json).
npm install yaml-to-envimport { yamlToEnv } from "yaml-to-env";
const yaml = `
port: 8080
host: 127.0.0.1
debug: false
`;
console.log(yamlToEnv(yaml));const { yamlToEnv } = require("yaml-to-env");
const yaml = `
port: 8080
host: 127.0.0.1
`;
console.log(yamlToEnv(yaml));Sample output:
PORT=8080
HOST=127.0.0.1
DEBUG=falseAfter npm install yaml-to-env, the yaml-to-env command is on your PATH when using npx or local node_modules/.bin.
| Invocation | Behavior |
|---|---|
yaml-to-env <input.yaml> |
Read the YAML file, convert it, print the result to stdout (no file is written). |
yaml-to-env <input.yaml> <out.env> |
Read the YAML file, convert it, write the result to out.env (UTF-8). Nothing is printed on success. |
Paths are resolved relative to the current working directory. More than two positional arguments is an error.
| Flag | Meaning |
|---|---|
-h, --help |
Print usage and exit 0. |
# Print dotenv lines to the terminal
npx yaml-to-env ./config/app.yaml
# Write .env next to your compose file
npx yaml-to-env ./config/values.yaml ./.env
# If the package is already a dependency
./node_modules/.bin/yaml-to-env ./config.yamlGlobal install: npm install -g yaml-to-env, then run yaml-to-env anywhere on your PATH.
Note: The CLI always uses default yamlToEnv / jsonToEnv options (same as the library with no second argument). For custom arrays, prefix, etc., use the JavaScript API or a small wrapper script.
The command for this package is yaml-to-env (with an e in env). A different, unmaintained package yaml-to-json pulls in old dependencies (natives, old graceful-fs) and often crashes on current Node with ReferenceError: primordials is not defined. If you see that stack trace, you are not running yaml-to-env — switch the package name and rerun, for example:
npx yaml-to-env path/to/config.yamlFrom a local clone (before publishing to npm): npm run build && node dist/cjs/cli.js path/to/config.yaml.
| Argument | Type | Description |
|---|---|---|
input |
string |
YAML source text. After parse, the document root must be a mapping ({} in JSON terms). |
options |
Options (optional) |
Passed through to @sourcepride/json-to-env jsonToEnv. Omitted fields use that library’s defaults. |
Returns: string — dotenv-style lines. An empty mapping at the root yields "".
| Export | Kind | Description |
|---|---|---|
yamlToEnv |
value | Main conversion function. |
Options |
type | Options bag for yamlToEnv; identical to Options from @sourcepride/json-to-env. |
For the full story on jsonToEnv (JSON5 roots, edge cases, and its own JSON CLI), see the json-to-env README.
- Root must be a mapping — e.g.
foo: baror---\nkey: value. A root that is only a list, a scalar,null, or an empty document throws aTypeError(mapping required). - Invalid YAML syntax — throws
Errorwith message starting withInvalid YAML inputand a short usage hint. - YAML → JSON snapshot — parsing uses the
yamlpackage; the resulting tree is what gets flattened (YAML-specific features like anchors/tags follow normalyamlparse semantics before conversion).
All fields are optional. This table matches @sourcepride/json-to-env; see its docs for examples and caveats.
| Value | Role |
|---|---|
"json" |
Default. Uses JavaScript array stringification; fine for primitives, awkward for objects inside arrays. |
"comma" |
join(",") into one variable. |
"indexed" |
NAME_0=…, NAME_1=…; objects in the array expand to NAME_0_FIELD=…. |
| Value | Role |
|---|---|
"flatten" |
Default. Recurse and emit one line per leaf (db.host → DB_HOST). |
"json" |
One line with the subtree as a JSON string value. |
"ignore" |
Omit that subtree (no lines). |
Ignored when separator is set (see below).
| Value | Typical result |
|---|---|
"upper_snake" |
Default. MY_APP_PORT |
"lower_snake" |
my_app_port |
"camel_case" |
myAppPort |
"pascal_case" |
MyAppPort |
"flat" |
Concatenated / uppercased segments |
| Field | Role |
|---|---|
prefix |
Prepended to every emitted variable name (e.g. APP_). |
separator |
If set, path parts are joined with this string and the key is uppercased; keyCase is not used for that path. |
YAML null and ~ map to JSON null; jsonToEnv emits those as empty values (same as the JSON path).
yamlToEnv(`
database:
host: db.example.com
port: 5432
`);DATABASE_HOST=db.example.com
DATABASE_PORT=5432yamlToEnv(
`
app:
name: demo
`,
{ prefix: "MYAPP", keyCase: "upper_snake" },
);MYAPP_APP_NAME=demoyamlToEnv(
`ids:
- 1
- 2
- 3
`,
{ arrays: "comma" },
);
// IDS=1,2,3
yamlToEnv(
`servers:
- a.example.com
- b.example.com
`,
{ arrays: "indexed" },
);
// SERVERS_0=a.example.com
// SERVERS_1=b.example.comyamlToEnv(
`meta:
region: us-east
tier: 1
`,
{ objects: "json" },
);META={"region":"us-east","tier":1}yamlToEnv(
`section:
value: x
`,
{ separator: "__" },
);SECTION__VALUE=x| Symptom | Likely cause |
|---|---|
TypeError: root must be a mapping |
Root YAML is a list, scalar only, or otherwise not a plain object. |
Error: Invalid YAML input |
Malformed YAML (indentation, structure, etc.). |
Errors from jsonToEnv after parse |
Rare for well-formed mapping roots; see json-to-env errors section (parse shape, arrays: "indexed" with bad keys, etc.). |
- Values are stringified like
jsonToEnv; the library does not add shell quotes. If values contain#, spaces, or newlines, downstream tools may need escaping or quoting in the file you write. - Key order follows the iteration order of the parsed object (YAML mapping order is preserved by the parser for typical documents).
- For JSON or JSON5 files from the shell, use the
json-to-envbinary from@sourcepride/json-to-env. This repo’syaml-to-envCLI is for YAML inputs only.
git clone https://github.com/Sourcepride/yaml-to-env.git
cd yaml-to-env
npm install
npm run typecheck
npm test
npm run buildnpm run build— emitsdist/cjsanddist/esm, writesdist/esm/package.jsonwith"type": "module", and copies the smalljson-to-env-loader.cjsbridge (so Node ESM consumers avoid a broken ESM graph in a dependency). Runnpm run buildbeforenpm testif you want the two integration tests that executedist/cjs/cli.js(they are skipped when that file is missing).
- @sourcepride/json-to-env — JSON / JSON5 / object input,
jsonToEnv, CLI, and fullOptionsdocumentation.
MIT — see LICENSE.