YAML

suggest change

YAML is a text format for structured data that people edit by hand. It is a superset of JSON with comments, no required quotes and indentation instead of braces, which is why Docker Compose, Kubernetes, GitHub Actions and OpenAPI use it.

Node.js has no built-in YAML support. There are two maintained packages:

Package Strengths
yaml YAML 1.2 and 1.1, keeps comments and formatting when editing, detailed errors, TypeScript types, no dependencies
js-yaml the older and most downloaded one; load() and dump()

Most of this article uses yaml. For loading YAML as one of several config sources (with env var overrides and validation), see Configuration files; this article covers the format and the library in more depth.

The examples were run with Node.js 24, yaml 2.9 and js-yaml 5.5, in a project whose package.json has "type": "module". Install with npm install yaml.

Parsing YAML

parse() turns a YAML string into plain JavaScript values:

import { parse } from 'yaml';

const text = `
name: shop-api
version: "2.4.0"
replicas: 3
ratio: 0.75
debug: false
owner: ~
started: 2026-10-17
tags: [web, api]
limits: { cpu: 500m, memory: 256Mi }
servers:
  - host: a.internal
    port: 8001
  - host: b.internal
    port: 8002
`;

const data = parse(text);
console.log(data);
console.log(typeof data.replicas, typeof data.started);
{
  name: 'shop-api',
  version: '2.4.0',
  replicas: 3,
  ratio: 0.75,
  debug: false,
  owner: null,
  started: '2026-10-17',
  tags: [ 'web', 'api' ],
  limits: { cpu: '500m', memory: '256Mi' },
  servers: [
    { host: 'a.internal', port: 8001 },
    { host: 'b.internal', port: 8002 }
  ]
}
number string

The building blocks:

Since YAML 1.2 is a superset of JSON, any JSON document parses too:

import { parse } from 'yaml';

console.log(parse('{"json": [1, 2, {"ok": true}]}'));
{ json: [ 1, 2, { ok: true } ] }

Strings and multi-line text

YAML has five ways to write a string. Block scalars (| and >) are the readable way to embed multi-line text such as scripts, SQL or certificates:

import { parse } from 'yaml';

const doc = parse(`
literal: |
  line one
  line two
folded: >
  this is a long
  sentence split
  over lines
stripped: |-
  no trailing newline
kept: |+
  keep all

single: 'it''s quoted'
double: "tab:\\there"
plain: no quotes needed
`);
for (const [k, v] of Object.entries(doc)) console.log(k.padEnd(9), JSON.stringify(v));
literal   "line one\nline two\n"
folded    "this is a long sentence split over lines\n"
stripped  "no trailing newline"
kept      "keep all\n\n"
single    "it's quoted"
double    "tab:\there"
plain     "no quotes needed"

Types depend on the schema

How a plain value is typed is decided by the schema. yaml uses the YAML 1.2 core schema by default, which is stricter than YAML 1.1 used by many older tools (PyYAML, older Ruby and Go libraries):

import { parse } from 'yaml';

const text = `
country: NO
enabled: yes
octal: 0o14
legacyOctal: 014
started: 2026-10-17
`;
console.log(parse(text));
console.log(parse(text, { version: '1.1' }));
console.log(parse(text, { schema: 'failsafe' }));
{
  country: 'NO',
  enabled: 'yes',
  octal: 12,
  legacyOctal: 14,
  started: '2026-10-17'
}
{
  country: false,
  enabled: true,
  octal: '0o14',
  legacyOctal: 12,
  started: 2026-10-17T00:00:00.000Z
}
{
  country: 'NO',
  enabled: 'yes',
  octal: '0o14',
  legacyOctal: '014',
  started: '2026-10-17'
}

In YAML 1.1 NO, yes, on and off are booleans (the "Norway problem"), 014 is octal and dates become Date objects. The failsafe schema makes every scalar a string, which is useful when you want to apply your own types.

Whatever the schema, numbers can surprise you: version: 1.10 is the number 1.1 and zip: 01234 loses its zero. Quote anything that must stay a string, and validate the loaded data (the Configuration files article shows validation with zod).

Writing YAML with stringify

stringify() converts JavaScript values to YAML. It quotes strings only when needed to keep their type:

import { stringify } from 'yaml';

const config = {
  name: 'shop-api',
  version: '2.4.0',
  zip: '01234',
  enabled: true,
  answer: 'yes',
  empty: null,
  skipped: undefined,
  started: new Date('2026-10-17T09:00:00Z'),
  description: 'First line\nSecond line\n',
  tags: ['web', 'api'],
  db: { host: 'localhost', port: 5432 },
};

console.log(stringify(config));
name: shop-api
version: 2.4.0
zip: "01234"
enabled: true
answer: yes
empty: null
started: 2026-10-17T09:00:00.000Z
description: |
  First line
  Second line
tags:
  - web
  - api
db:
  host: localhost
  port: 5432

Things to notice:

Options control the layout. A replacer function (or array of keys) works like the one in JSON.stringify():

import { stringify } from 'yaml';

const data = { b: 2, a: { list: [1, 2, 3], name: 'x' }, msg: 'hello' };

console.log(stringify(data, { indent: 4, sortMapEntries: true }));
console.log(stringify(data, { collectionStyle: 'flow' }));
console.log(stringify(data, { defaultStringType: 'QUOTE_DOUBLE', defaultKeyType: 'PLAIN' }));
console.log(stringify(data, (key, value) => (key === 'list' ? undefined : value)));
a:
    list:
        - 1
        - 2
        - 3
    name: x
b: 2
msg: hello

{ b: 2, a: { list: [ 1, 2, 3 ], name: x }, msg: hello }

b: 2
a:
  list:
    - 1
    - 2
    - 3
  name: "x"
msg: "hello"

b: 2
a:
  name: x
msg: hello

Other useful options are lineWidth (default 80, 0 disables folding of long strings) and nullStr (for example '~').

Anchors, aliases and merge keys

An anchor (&name) labels a node and an alias (*name) refers to it. The << merge key copies the keys of a mapping into another one. Merge keys were part of YAML 1.1 only, so yaml needs merge: true to support them in 1.2 mode:

import { parse, stringify } from 'yaml';

const text = `
base: &base
  image: node:24
  restart: always
web:
  <<: *base
  ports: [8000]
worker:
  <<: *base
  restart: on-failure
hosts: &hosts [a, b]
backup: *hosts
`;

const data = parse(text, { merge: true });
console.log(data.web);
console.log(data.worker);
console.log(data.backup === data.hosts);

// shared objects are written as anchors and aliases
const shared = { level: 'info' };
console.log(stringify({ app: shared, audit: shared }));
console.log(stringify({ app: shared, audit: shared }, { aliasDuplicateObjects: false }));
{ image: 'node:24', restart: 'always', ports: [ 8000 ] }
{ image: 'node:24', restart: 'on-failure' }
true
{ level: 'info' }
app: &a1
  level: info
audit: *a1

app:
  level: info
audit:
  level: info

Keys written after << override merged ones. An alias gives you the same object, not a copy (data.backup === data.hosts), so mutating one changes the other. When writing YAML for tools that don't handle aliases well, pass aliasDuplicateObjects: false.

Multiple documents in one file

A --- line starts a new document. Kubernetes manifests often put several resources in one file. parse() refuses such input; use parseAllDocuments():

apiVersion: v1
kind: Service
metadata:
  name: shop
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop
spec:
  replicas: 3
---
# empty document is allowed
import { readFile } from 'node:fs/promises';
import { parse, parseAllDocuments, stringify } from 'yaml';

const text = await readFile('k8s.yaml', 'utf8');

try {
  parse(text);
} catch (err) {
  console.log(err.code);
}

const docs = parseAllDocuments(text);
for (const doc of docs) {
  if (doc.errors.length) throw doc.errors[0];
  const obj = doc.toJS();
  console.log(obj ? `${obj.kind}/${obj.metadata.name}` : '(empty)');
}

// writing several documents: join with ---
const out = [{ kind: 'A' }, { kind: 'B' }].map((o) => stringify(o)).join('---\n');
console.log(out);
MULTIPLE_DOCS
Service/shop
Deployment/shop
(empty)
kind: A
---
kind: B

Errors and warnings

parse() throws a YAMLParseError for the first error. The error has a code, a character range in pos and line/column in linePos, and its message includes a snippet of the source:

import { parse, parseDocument } from 'yaml';

const bad = `db:
  host: localhost
  port: 5432
  host: db.internal
features: [search, export
`;

try {
  parse(bad);
} catch (err) {
  console.log(err.name, err.code);
  console.log(err.message);
  console.log('---');
}

// parseDocument() never throws; it collects all problems
const doc = parseDocument(bad);
for (const e of doc.errors) {
  const { line, col } = e.linePos[0];
  console.log(`${line}:${col} ${e.code}`);
}
console.log(doc.warnings.length);

// duplicate keys can be allowed (last one wins)
console.log(parse('a: 1\na: 2\n', { uniqueKeys: false }));
YAMLParseError DUPLICATE_KEY
Map keys must be unique at line 4, column 3:

  port: 5432
  host: db.internal
  ^

---
4:3 DUPLICATE_KEY
6:1 BAD_INDENT
0
{ a: 2 }

Duplicate keys are an error by default. Many other parsers silently keep the last value, which hides copy-paste mistakes in config files.

Non-fatal problems are warnings. parse() prints them with process.emitWarning(), for example for an unknown tag:

(node:13076) [TAG_RESOLVE_FAILED] YAMLWarning: Unresolved tag: !vault at line 1, column 9:

secret: !vault abc123
        ^^^^^^

Pass { logLevel: 'error' } to silence them, or use parseDocument() and inspect doc.warnings yourself. Here is a small loader that puts the file name in front of every message:

import { readFile } from 'node:fs/promises';
import { parseDocument } from 'yaml';

async function loadYaml(path, options) {
  const text = await readFile(path, 'utf8');
  const doc = parseDocument(text, options);
  for (const w of doc.warnings) console.warn(`${path}: ${w.message}`);
  if (doc.errors.length > 0) throw new Error(`${path}: ${doc.errors[0].message}`);
  return doc.toJS();
}

console.log(await loadYaml('config.yaml'));
try {
  await loadYaml('broken.yaml');
} catch (err) {
  console.log(err.message);
}
{
  port: 8000,
  db: { host: 'localhost', port: 5432 },
  features: [ 'search' ]
}
broken.yaml: Nested mappings are not allowed in compact mappings at line 3, column 9:

  host: localhost
        ^

broken.yaml has one extra space before port: on line 4. YAML reported the error on the previous line because, with the extra indentation, port: 5432 looks like a continuation of the value localhost. With indentation errors, look at the lines around the reported position.

Editing files and keeping comments

parse() and stringify() lose comments, blank lines and quoting style. To change a hand-written file without destroying it, use parseDocument(), which returns a Document with a tree of nodes. Here is config.yaml:

# Shop API configuration
port: 8000 # HTTP port

db:
  host: localhost
  port: 5432

# enabled feature flags
features:
  - search
import { readFile, writeFile } from 'node:fs/promises';
import { parseDocument } from 'yaml';

const doc = parseDocument(await readFile('config.yaml', 'utf8'));

console.log(doc.get('port'));
console.log(doc.getIn(['db', 'host']));

doc.set('port', 9000);
doc.setIn(['db', 'host'], 'db.internal');
doc.addIn(['features'], 'export');
doc.setIn(['cache', 'ttlSeconds'], 60);
doc.deleteIn(['db', 'port']);

await writeFile('config.out.yaml', doc.toString());
console.log(doc.toString());
console.log(doc.toJS());
8000
localhost
# Shop API configuration
port: 9000 # HTTP port

db:
  host: db.internal

# enabled feature flags
features:
  - search
  - export
cache:
  ttlSeconds: 60

{
  port: 9000,
  db: { host: 'db.internal' },
  features: [ 'search', 'export' ],
  cache: { ttlSeconds: 60 }
}

get, set, has, delete and add work on one level; the ...In versions take a path of keys and indexes. setIn creates missing intermediate maps. doc.toJS() gives the plain JavaScript value.

Nodes can carry comments, which is handy for generated files. Pass true as the second argument of get() to get the node instead of its value:

import { parseDocument, isScalar } from 'yaml';

const doc = parseDocument('port: 8000\n');
doc.commentBefore = ' generated by deploy.js, do not edit';

// createPair() turns both key and value into nodes that can carry comments
const pair = doc.createPair('cache', { ttlSeconds: 60 });
pair.key.commentBefore = ' cache settings';
pair.key.spaceBefore = true; // blank line before the comment
pair.value.get('ttlSeconds', true).comment = ' seconds';
doc.add(pair);

// get(key, true) returns the node instead of its plain value
const port = doc.get('port', true);
console.log(isScalar(port), port.value, port.range);
console.log(doc.toString());
true 8000 [ 6, 10, 11 ]
# generated by deploy.js, do not edit

port: 8000

# cache settings
cache:
  ttlSeconds: 60 # seconds

range is the node's position in the source text, which lets you report "line N" in your own validation errors. isScalar, isMap, isSeq, isPair and isAlias identify node types, and visit() walks the whole tree.

Custom tags

A tag (!name) tells the parser how to construct a value. Add your own with customTags. A common use is reading secrets from environment variables, so the file itself never contains them:

import { parse } from 'yaml';

// !env NAME  ->  value of process.env.NAME
const envTag = {
  tag: '!env',
  resolve(str, onError) {
    const value = process.env[str];
    if (value === undefined) onError(`environment variable ${str} is not set`);
    return value;
  },
};

// !duration 1h30m  ->  milliseconds
const durationTag = {
  tag: '!duration',
  resolve(str, onError) {
    const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(str);
    if (!m || str === '') return onError(`bad duration: ${str}`);
    const [, h = 0, min = 0, s = 0] = m;
    return ((+h * 60 + +min) * 60 + +s) * 1000;
  },
};

process.env.DB_PASSWORD = 's3cret';

const text = `
db:
  user: shop
  password: !env DB_PASSWORD
sessionTtl: !duration 1h30m
requestTimeout: !duration 15s
`;
const config = parse(text, { customTags: [envTag, durationTag] });
console.log(config);

try {
  parse('key: !env MISSING_VAR\n', { customTags: [envTag] });
} catch (err) {
  console.log(err.message.split('\n')[0]);
}
{
  db: { user: 'shop', password: 's3cret' },
  sessionTtl: 5400000,
  requestTimeout: 15000
}
environment variable MISSING_VAR is not set at line 1, column 6:

Errors reported with onError get the position of the tagged value added to them.

To also write a type, add identify (which values the tag handles) and stringify:

import { parse, stringify } from 'yaml';

const urlTag = {
  tag: '!url',
  identify: (value) => value instanceof URL, // used by stringify()
  resolve: (str) => new URL(str),            // used by parse()
  stringify: ({ value }) => value.href,
};

const opts = { customTags: [urlTag] };

const text = stringify({ api: new URL('https://api.example.com/v2/'), name: 'billing' }, opts);
console.log(text);

const back = parse(text, opts);
console.log(back.api instanceof URL, back.api.host);
api: !url https://api.example.com/v2/
name: billing

true api.example.com

Non-string keys

YAML keys can be numbers, booleans or even collections, but JavaScript object keys are strings. By default they're converted to strings; with mapAsMap: true you get Map objects with the original keys:

import { parse } from 'yaml';

const text = `
1: one
true: yes
[a, b]: pair
`;
console.log(parse(text));
console.log(parse(text, { mapAsMap: true }));
{ '1': 'one', true: 'yes', '[ a, b ]': 'pair' }
Map(3) { 1 => 'one', true => 'yes', [ 'a', 'b' ] => 'pair' }

The first call also prints a warning about the collection key being stringified.

Untrusted input

YAML from users or the network needs some care:

import { parse } from 'yaml';

// "billion laughs": each level multiplies the size by 10
const bomb = `
a: &a [x, x, x, x, x, x, x, x, x, x]
b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a]
c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b]
d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c, *c]
e: &e [*d, *d, *d, *d, *d, *d, *d, *d, *d, *d]
f: &f [*e, *e, *e, *e, *e, *e, *e, *e, *e, *e]
`;

try {
  parse(bomb);
} catch (err) {
  console.log(err.name);
  console.log(err.message);
}
ReferenceError
Excessive alias count indicates a resource exhaustion attack

Using js-yaml

js-yaml has a smaller API: load(), loadAll() and dump(). Like yaml, it uses the YAML 1.2 core schema and leaves merge keys off by default; enable them by adding mergeTag to the schema:

import { load, loadAll, dump, CORE_SCHEMA, mergeTag, YAMLException } from 'js-yaml';

const text = `
base: &base { retries: 3, timeoutMs: 2000 }
payments:
  <<: *base
  timeoutMs: 5000
`;

const schema = CORE_SCHEMA.withTags(mergeTag);
console.log(load(text, { schema }).payments);

console.log(loadAll('a: 1\n---\nb: 2\n'));

console.log(dump({ name: 'shop', zip: '01234', tags: ['web', 'api'] }, { indent: 2 }));

try {
  load('a: [1, 2');
} catch (err) {
  console.log(err instanceof YAMLException, err.message.split('\n')[0]);
}
{ retries: 3, timeoutMs: 5000 }
[ { a: 1 }, { b: 2 } ]
name: shop
zip: '01234'
tags:
  - web
  - api

true unexpected end of the stream within a flow collection (1:9)

Pick js-yaml if a project already depends on it. Choose yaml if you need to edit files and keep their comments, or want error positions and warnings you can inspect.

Command-line conversion

The yaml package includes a small CLI that reads stdin. It's handy for converting files to JSON or checking them in CI scripts:

$ npx yaml --json --indent 2 < config.yaml
[
  {
    "port": 8000,
    "db": {
      "host": "localhost",
      "port": 5432
    },
    "features": [
      "search"
    ]
  }
]
$ npx yaml valid < config.yaml
$ echo $?
0

yaml valid prints nothing and exits with status 0 when the input is valid. For invalid input it prints the YAMLParseError to stderr and exits with status 1. --json always outputs an array, one element per document.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents