{"id":16096,"library":"js-yaml","title":"YAML 1.2 Parser and Serializer for JavaScript","description":"JS-YAML is a high-performance JavaScript library for parsing and serializing YAML 1.2 documents. Originally inspired by PyYAML, it underwent a complete rewrite to optimize for speed and full adherence to the latest YAML specification. The current stable version, 4.1.1, offers robust functionalities including both 'safe' and 'full' modes for loading and dumping YAML data, catering to various security and feature requirements. It maintains a regular release cadence for bug fixes and minor improvements, with major versions introducing significant API or feature changes. Key differentiators include its speed, comprehensive support for YAML 1.2 tags, and a strong emphasis on providing a secure parsing option via `safeLoad`, which limits potentially unsafe features like arbitrary code execution. While primarily used in Node.js, it also provides a browser-compatible build, though its browser support is explicitly noted as less thoroughly tested and may require additional shims for older environments.","status":"active","version":"4.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/nodeca/js-yaml","tags":["javascript","yaml","parser","serializer","pyyaml"],"install":[{"cmd":"npm install js-yaml","lang":"bash","label":"npm"},{"cmd":"yarn add js-yaml","lang":"bash","label":"yarn"},{"cmd":"pnpm add js-yaml","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for parsing `!!js/function` tags in browser environments.","package":"esprima","optional":true},{"reason":"Required for browser support in older browsers like IE.","package":"es5-shim","optional":true}],"imports":[{"note":"This is the standard CommonJS import for the entire module object. For ESM modules, `import * as yaml from 'js-yaml';` is also supported.","wrong":"import * as yaml from 'js-yaml';","symbol":"yaml","correct":"const yaml = require('js-yaml');"},{"note":"This is the recommended method for parsing YAML from untrusted sources, as it explicitly disables dangerous tags like `!!js/function`. It can be imported via named import in ESM or destructured from `require` in CommonJS (`const { safeLoad } = require('js-yaml');`).","symbol":"safeLoad","correct":"import { safeLoad } from 'js-yaml';"},{"note":"Use `safeDump` to serialize objects into standard YAML, avoiding potentially non-standard or unsafe tags that the generic `dump` method might produce. Available as a named import in ESM or destructured from `require` in CommonJS.","symbol":"safeDump","correct":"import { safeDump } from 'js-yaml';"}],"quickstart":{"code":"const yaml = require('js-yaml');\nconst fs = require('fs');\nconst path = require('path');\n\n// Example YAML content to parse\nconst yamlContent = `\ngreeting: hello\nname: world\nversion: 1.0\nconfig:\n  enabled: true\n  port: 3000\ndata:\n  - item1\n  - item2\n`;\n\n// Create a dummy YAML file for demonstration purposes\nconst tempFilePath = path.join(__dirname, 'example.yml');\nfs.writeFileSync(tempFilePath, yamlContent, 'utf8');\n\ntry {\n  // Use safeLoad to parse the YAML content from the dummy file\n  const doc = yaml.safeLoad(fs.readFileSync(tempFilePath, 'utf8'));\n  console.log('Successfully loaded YAML document:');\n  console.log(JSON.stringify(doc, null, 2));\n\n  // Example of dumping a JavaScript object back into YAML format\n  const dataToDump = {\n    title: 'My Document',\n    author: 'AI Agent',\n    date: new Date().toISOString().split('T')[0] // Format date for YAML\n  };\n  const dumpedYaml = yaml.safeDump(dataToDump); // safeDump is also preferred for output\n  console.log('\\nSuccessfully dumped object to YAML:');\n  console.log(dumpedYaml);\n\n} catch (e) {\n  console.error('Error processing YAML:', e.message);\n} finally {\n  // Clean up the dummy file after use\n  if (fs.existsSync(tempFilePath)) {\n    fs.unlinkSync(tempFilePath);\n  }\n}","lang":"javascript","description":"This quickstart demonstrates how to load YAML from a file using `safeLoad` and serialize a JavaScript object to YAML using `safeDump`, emphasizing safe practices."},"warnings":[{"fix":"Prior to v4.0.0, duplicate keys in YAML mappings might have silently overwritten values or had undefined behavior. From v4.0.0, parsing YAML with duplicate keys will throw a `YAMLException`. To replicate `JSON.parse` behavior where the last key overrides previous ones, set the `json: true` option in `safeLoad` or `load`: `yaml.safeLoad(data, { json: true })`.","message":"Duplicate keys in YAML mappings now throw an error by default.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Always prefer `yaml.safeLoad()` for parsing YAML from untrusted or external sources to prevent arbitrary code execution via dangerous JavaScript-specific tags (e.g., `!!js/function`, `!!js/regexp`). Similarly, use `yaml.safeDump()` for generating standard YAML output.","message":"Using `yaml.load()` or `yaml.dump()` can introduce security vulnerabilities or produce non-standard output with untrusted input.","severity":"gotcha","affected_versions":"*"},{"fix":"The browser bundle is not extensively tested by maintainers. Be aware that `!!js/function` requires `esprima` to be loaded separately, and `!!bin` tags will return JavaScript `Array` instances instead of Node.js `Buffer` objects. Older browsers may require `es5-shims`.","message":"Limited and less tested browser support for `js-yaml`.","severity":"gotcha","affected_versions":"*"},{"fix":"If you intend to parse `!!js/function` tags in a browser environment, you must explicitly load the `esprima.js` parser before `js-yaml.min.js`. This functionality is generally discouraged for security reasons with untrusted input, as it allows arbitrary code execution.","message":"The `!!js/function` tag requires `esprima` for proper parsing in browsers and is a security risk.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Carefully review the YAML content, specifically around the indicated line and column, for consistent spacing and proper nesting. YAML uses spaces, not tabs, for indentation.","cause":"The YAML document has incorrect indentation, which is critical for YAML's structure.","error":"YAMLException: bad indentation of a mapping entry (line X, column Y)"},{"fix":"Ensure the package is installed by running `npm install js-yaml` or `yarn add js-yaml`. Verify that the import statement correctly references the package name, e.g., `const yaml = require('js-yaml');` or `import { safeLoad } from 'js-yaml';`.","cause":"The 'js-yaml' package is not installed in the project or the import path is incorrect.","error":"Error: Cannot find module 'js-yaml'"},{"fix":"Implement defensive programming by checking for `null` or `undefined` values before accessing properties, especially for optional YAML fields. Use optional chaining (`?.`) or nullish coalescing (`??`) if your environment supports it.","cause":"Attempting to access a property on an object that was parsed as `undefined` or `null` from the YAML document.","error":"TypeError: Cannot read properties of undefined (reading 'someProperty')"}],"ecosystem":"npm"}