Introduction to js-yaml
js-yaml is an awesome library for parsing and dumping YAML in JavaScript. It allows for easy manipulation and conversion of YAML data to JavaScript objects and vice versa. With a wide range of APIs, js-yaml makes working with YAML a seamless experience.
Basic Usage
1. Parsing YAML to JavaScript Object
const yaml = require('js-yaml'); const fs = require('fs'); try { const doc = yaml.load(fs.readFileSync('document.yaml', 'utf8')); console.log(doc); } catch (e) { console.log(e); }
2. Dumping JavaScript Object to YAML
const yaml = require('js-yaml'); const obj = { name: 'John', age: 30, city: 'New York' }; const yamlStr = yaml.dump(obj); console.log(yamlStr);
3. Schema Customization
const yaml = require('js-yaml'); const CUSTOM_SCHEMA = yaml.DEFAULT_SCHEMA.extend({ implicit: [new yaml.Type('!date', { kind: 'scalar', resolve: data => /\d{4}-\d{2}-\d{2}/.test(data), construct: data => new Date(data) })] }); const data = yaml.load('birthday: 1990-01-01', { schema: CUSTOM_SCHEMA }); console.log(data.birthday.toISOString());
4. Creating Custom YAML Types
const yaml = require('js-yaml'); const PointType = new yaml.Type('!point', { kind: 'scalar', construct: data => data.split(',').map(Number), instanceOf: Array, }); const schema = yaml.Schema.create([ PointType ]); const doc = yaml.load('point: 1,2,3', { schema: schema }); console.log(doc);
Advanced Techniques
5. Using Safe Load and Safe Dump
const yaml = require('js-yaml'); // Load a YAML document safely const doc = yaml.safeLoad(fs.readFileSync('input.yaml', 'utf8')); // Dump a JavaScript object safely const yamlStr = yaml.safeDump(doc); console.log(yamlStr);
6. Error Handling
const yaml = require('js-yaml'); try { const doc = yaml.load('invalid: yaml:'); } catch (e) { console.error(e.message); }
Application Example
Let’s create an example application that reads a YAML file, modifies the data, and writes it back to a YAML file. We will use several APIs demonstrated above.
const yaml = require('js-yaml'); const fs = require('fs'); // Read data from YAML file let data; try { data = yaml.load(fs.readFileSync('input.yaml', 'utf8')); } catch (e) { console.error('Error reading YAML file:', e); return; } // Modify the data data.age += 1; // Write data back to YAML file try { fs.writeFileSync('output.yaml', yaml.dump(data)); console.log('Data written to output.yaml:', data); } catch (e) { console.error('Error writing YAML file:', e); }
By utilizing js-yaml, we can easily manage YAML data within our JavaScript applications, making it a powerful tool for configuration and data serialization.
Hash: e68affe23118fe6e26fb140d257a178af8f8e6f151ac17bcc1fb40defaf5984a