YAML 1.2 parser and serializer for JavaScript environments with complete specification support
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
The dumping functionality in js-yaml provides comprehensive YAML serialization capabilities, converting JavaScript objects to YAML strings with extensive formatting and style control options.
Serializes a JavaScript object as a YAML document string.
function dump(input, options);Parameters:
input (any): JavaScript value to serialize (object, array, string, number, boolean, null)options (DumpOptions, optional): Serialization configuration optionsReturns: YAML string representation of the input
Throws: YAMLException if input contains non-serializable values (unless skipInvalid: true)
Usage Examples:
const yaml = require('js-yaml');
// Basic serialization
const obj = {
name: 'John Doe',
age: 30,
skills: ['JavaScript', 'YAML', 'Node.js'],
active: true
};
const yamlString = yaml.dump(obj);
console.log(yamlString);interface DumpOptions {
indent?: number;
noArrayIndent?: boolean;
skipInvalid?: boolean;
flowLevel?: number;
styles?: object;
schema?: Schema;
sortKeys?: boolean | ((a: string, b: string) => number);
lineWidth?: number;
noRefs?: boolean;
noCompatMode?: boolean;
condenseFlow?: boolean;
quotingType?: '"' | "'";
forceQuotes?: boolean;
replacer?: (key: string, value: any) => any;
}indent - Controls indentation width in spaces (default: 2):
yaml.dump(obj, { indent: 4 });
// Output with 4-space indentationnoArrayIndent - When true, doesn't add indentation level to array elements:
const data = { items: ['a', 'b', 'c'] };
// Default behavior
yaml.dump(data);
// items:
// - a
// - b
// With noArrayIndent: true
yaml.dump(data, { noArrayIndent: true });
// items:
// - a
// - bskipInvalid - Skip invalid types instead of throwing errors:
const objWithFunction = {
name: 'test',
callback: function() { return 'hello'; },
data: [1, 2, 3]
};
// Throws error by default
try {
yaml.dump(objWithFunction);
} catch (e) {
console.log('Cannot serialize function');
}
// Skip invalid types
const result = yaml.dump(objWithFunction, { skipInvalid: true });
// Only serializes 'name' and 'data', skips 'callback'flowLevel - Controls when to switch from block to flow style (-1 = always block):
const nested = {
level1: {
level2: {
level3: { key: 'value' }
}
}
};
// Always block style (default)
yaml.dump(nested, { flowLevel: -1 });
// Switch to flow at level 2
yaml.dump(nested, { flowLevel: 1 });
// level1:
// level2: { level3: { key: value } }sortKeys - Sort object keys in output:
const unordered = { z: 1, a: 2, m: 3 };
// Sort alphabetically
yaml.dump(unordered, { sortKeys: true });
// a: 2
// m: 3
// z: 1
// Custom sort function
yaml.dump(unordered, {
sortKeys: (a, b) => b.localeCompare(a) // Reverse alphabetical
});lineWidth - Maximum line width for text wrapping (default: 80, -1 = unlimited):
const longText = { description: 'A very long text that exceeds normal line width...' };
yaml.dump(longText, { lineWidth: 40 });
// description: >-
// A very long text that exceeds normal
// line width...
yaml.dump(longText, { lineWidth: -1 });
// No line wrappingnoRefs - Disable object reference conversion for duplicate objects:
const shared = { shared: 'data' };
const obj = { ref1: shared, ref2: shared };
// Default: uses YAML references
yaml.dump(obj);
// ref1: &ref_0
// shared: data
// ref2: *ref_0
// With noRefs: true
yaml.dump(obj, { noRefs: true });
// ref1:
// shared: data
// ref2:
// shared: dataquotingType - Preferred quote style for strings:
const strings = { single: "text with 'quotes'", double: 'text with "quotes"' };
yaml.dump(strings, { quotingType: '"' });
// Use double quotes when needed
yaml.dump(strings, { quotingType: "'" });
// Use single quotes when needed (default)forceQuotes - Force quote all non-key strings:
const data = { key: 'simple text', number: '123' };
yaml.dump(data, { forceQuotes: true });
// key: 'simple text'
// number: '123'noCompatMode - Disable YAML 1.1 compatibility features:
const booleans = { yes: true, no: false, on: true };
// Default: quotes ambiguous values for YAML 1.1 compatibility
yaml.dump(booleans);
// 'yes': true
// 'no': false
// With noCompatMode: true
yaml.dump(booleans, { noCompatMode: true });
// yes: true
// no: falsecondenseFlow - Condense flow sequences and mappings:
const flow = { list: ['a', 'b', 'c'], map: { x: 1, y: 2 } };
yaml.dump(flow, { flowLevel: 0, condenseFlow: true });
// {list: [a,b,c], map: {x: 1,y: 2}}schema - Specify schema for serialization:
yaml.dump(data, { schema: yaml.JSON_SCHEMA });
// Only uses JSON-compatible typesreplacer - Transform values during serialization:
const data = {
created: new Date('2023-01-01'),
secret: 'password123',
value: 42
};
yaml.dump(data, {
replacer: (key, value) => {
if (key === 'secret') return '[REDACTED]';
if (value instanceof Date) return value.toISOString();
return value;
}
});Control how specific YAML types are formatted using the styles option:
interface StylesMap {
[tagName: string]: string;
}!!null styles:
"canonical" → "~""lowercase" → "null" (default)"uppercase" → "NULL""camelcase" → "Null"!!int styles:
"binary" → "0b1101""octal" → "0o15""decimal" → "13" (default)"hexadecimal" → "0xD"!!bool styles:
"lowercase" → "true", "false" (default)"uppercase" → "TRUE", "FALSE""camelcase" → "True", "False"!!float styles:
"lowercase" → ".nan", ".inf" (default)"uppercase" → ".NAN", ".INF""camelcase" → ".NaN", ".Inf"const data = {
active: null,
count: 42,
flag: true,
ratio: Number.POSITIVE_INFINITY
};
yaml.dump(data, {
styles: {
'!!null': 'canonical', // Use ~ for null
'!!int': 'hexadecimal', // Use hex for integers
'!!bool': 'uppercase', // Use TRUE/FALSE
'!!float': 'uppercase' // Use .INF/.NAN
}
});
// Output:
// active: ~
// count: 0x2A
// flag: TRUE
// ratio: .INFfunction generateConfig(config) {
return yaml.dump(config, {
indent: 2,
lineWidth: 120,
sortKeys: true,
noCompatMode: true,
styles: {
'!!null': 'lowercase',
'!!bool': 'lowercase'
}
});
}function exportData(data, format = 'readable') {
const options = {
readable: {
indent: 2,
lineWidth: 80,
flowLevel: -1
},
compact: {
indent: 0,
lineWidth: -1,
flowLevel: 0,
condenseFlow: true
},
safe: {
skipInvalid: true,
noRefs: true,
schema: yaml.CORE_SCHEMA
}
};
return yaml.dump(data, options[format] || options.readable);
}