@sourcepride/yaml-to-env
v1.0.0
Published
YAML to .env converter for Node: turn YAML config into dotenv KEY=value lines (flatten nested maps, arrays, objects), with key casing and prefixes. Works with CommonJS and ES modules. Use for Docker env files, Kubernetes secrets, GitHub Actions, and twelv
Maintainers
Readme
yaml-to-env
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.
Features
- 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.
Requirements
- Node.js ≥ 14 (see
enginesinpackage.json).
Install
npm install yaml-to-envQuick start
ESM
import { yamlToEnv } from "yaml-to-env";
const yaml = `
port: 8080
host: 127.0.0.1
debug: false
`;
console.log(yamlToEnv(yaml));CommonJS
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=falseCLI
After 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.
Options
| Flag | Meaning |
| ---- | ------- |
| -h, --help | Print usage and exit 0. |
Examples
# 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.
Name on npm (yaml-to-env vs yaml-to-json)
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.
API
yamlToEnv(input, options?)
| 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 "".
Exports (yaml-to-env)
| 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.
YAML-specific rules
- 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).
Options (summary)
All fields are optional. This table matches @sourcepride/json-to-env; see its docs for examples and caveats.
arrays — top-level array properties only
| 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=…. |
objects — nested plain object values
| 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). |
keyCase — how path segments become env names
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 |
Other fields
| 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. |
null / undefined in YAML
YAML null and ~ map to JSON null; jsonToEnv emits those as empty values (same as the JSON path).
Examples
Nested mapping (default flatten)
yamlToEnv(`
database:
host: db.example.com
port: 5432
`);DATABASE_HOST=db.example.com
DATABASE_PORT=5432Prefix and key case
yamlToEnv(
`
app:
name: demo
`,
{ prefix: "MYAPP", keyCase: "upper_snake" },
);MYAPP_APP_NAME=demoArrays: comma vs indexed
yamlToEnv(
`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.comNested object as one JSON value
yamlToEnv(
`meta:
region: us-east
tier: 1
`,
{ objects: "json" },
);META={"region":"us-east","tier":1}Separator instead of snake rules
yamlToEnv(
`section:
value: x
`,
{ separator: "__" },
);SECTION__VALUE=xErrors you might see
| 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.). |
Practical notes
- 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.
Development
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).
Related
- @sourcepride/json-to-env — JSON / JSON5 / object input,
jsonToEnv, CLI, and fullOptionsdocumentation.
License
MIT (see package.json).
