Skip to content

Sourcepride/yaml-to-env

Repository files navigation

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, .env lines out — nested mappings become flattened keys by default (db.hostDB_HOST=…).
  • Same Options as jsonToEnvarrays, objects, keyCase, prefix, separator (TypeScript type re-exported from this package).
  • Dual module formatsCommonJS (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 .env file.
  • 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 engines in package.json).

Install

npm install yaml-to-env

Quick 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=false

CLI

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.yaml

Global 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.yaml

From 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

  1. Root must be a mapping — e.g. foo: bar or ---\nkey: value. A root that is only a list, a scalar, null, or an empty document throws a TypeError (mapping required).
  2. Invalid YAML syntax — throws Error with message starting with Invalid YAML input and a short usage hint.
  3. YAML → JSON snapshot — parsing uses the yaml package; the resulting tree is what gets flattened (YAML-specific features like anchors/tags follow normal yaml parse 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.hostDB_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=5432

Prefix and key case

yamlToEnv(
  `
app:
  name: demo
`,
  { prefix: "MYAPP", keyCase: "upper_snake" },
);
MYAPP_APP_NAME=demo

Arrays: 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.com

Nested 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=x

Errors 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-env binary from @sourcepride/json-to-env. This repo’s yaml-to-env CLI 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 build
  • npm run build — emits dist/cjs and dist/esm, writes dist/esm/package.json with "type": "module", and copies the small json-to-env-loader.cjs bridge (so Node ESM consumers avoid a broken ESM graph in a dependency). Run npm run build before npm test if you want the two integration tests that execute dist/cjs/cli.js (they are skipped when that file is missing).

Related

License

MIT — see LICENSE.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors