Introduction to js-yaml
js-yaml is a popular JavaScript library used for parsing and stringifying YAML, a human-readable data serialization standard. This library allows developers to seamlessly convert YAML data into JavaScript objects and vice versa, facilitating easy data manipulation and configuration in web applications.
Basic Usage of js-yaml
Loading YAML into JavaScript
To load a YAML string into a JavaScript object, use the yaml.load
method:
const yaml = require('js-yaml'); const fs = require('fs'); const fileContent = fs.readFileSync('example.yaml', 'utf8'); const data = yaml.load(fileContent); console.log(data); // Outputs the JavaScript object
Dumping JavaScript to YAML
To convert a JavaScript object back into a YAML string, use the yaml.dump
method:
const yaml = require('js-yaml'); const data = { title: "Example", description: "This is a description" }; const yamlString = yaml.dump(data); console.log(yamlString); // Outputs the YAML string
Advanced Features
Error Handling
You can handle errors while parsing YAML using try-catch blocks:
try { const data = yaml.load('invalid: [yaml'); } catch (e) { console.error(e.message); // Handles and logs the error }
Custom YAML Types
You can define custom YAML types for specific use cases:
const schema = yaml.DEFAULT_SCHEMA.extend([{ kind: 'scalar', resolve: data => data === 'custom', construct: data => 'This is a custom type' }]); const data = yaml.load('value: custom', { schema }); console.log(data); // { value: 'This is a custom type' }
Example App
Here’s an example app that reads a YAML configuration file and uses it to configure an application:
const yaml = require('js-yaml'); const fs = require('fs'); const configFile = 'config.yaml'; let config = {}; try { const fileContent = fs.readFileSync(configFile, 'utf8'); config = yaml.load(fileContent); } catch (e) { console.error('Failed to load config:', e.message); } const app = { name: config.name || 'Default App', port: config.port || 3000 }; console.log(`Starting ${app.name} on port ${app.port}`);
This application reads the configuration settings from config.yaml
and uses them to set up the app.