This tutorial explains How to read and write YAML files in NodeJS Javascript.

How to read/write YAML file in Javascript

There are many parser libraries available to parse and write in Nodejs.

  • yaml npm
  • js-toml library

This post is an example of reading and writing a yaml file using the js-yaml npm library. js-yaml is a popular library in Java used to convert JSON/XML to/from Java objects.

First, Install the js-yaml library in a project in terminal

 E:\work\nodejs-examples> npm install js-yaml

Sample Yaml file example for read:

yaml is a superset of json and human-readable format. It contains key and value pairs with included indentation and tabs.

Below is the yaml example file with database dictionary details.

--- # Application configuration - config.yaml
author: Franc
database:
  driver: com.mysql.jdbc.Driver
  port: 3306
  dbname: students
  username: root
  password: root
support:
  - mysql
  - MongoDB
  - Postgres

Parse/Read yaml file into an object in Node Javascript

First, Read the yaml file using the fs.readFileSync() function with encoding, and outputs the filecontent. Next, filecontent is passed to the yaml.load() function, Returns the Javascript object. Read the object data using dot notation.

Here is an example

const fs = require('fs');
const yaml = require('js-yaml');

try {
    const yamlData = yaml.load(fs.readFileSync('config.yaml', 'utf8'));
    console.log(yamlData);
    console.log(yamlData.author);
    console.log(yamlData.support);


} catch (error) {
    console.error(error);
}

Output on Running the above code

E:\work\nodejs-examples> node read-yaml.js
{
  author: 'Franc',
  database: {
    driver: 'com.mysql.jdbc.Driver',
    port: 3306,
    dbname: 'students',
    username: 'root',
    password: 'root'
  },
  support: [ 'mysql', 'Mongodb', 'Postgres' ]
}
Franc
[ 'mysql', 'mongodb', 'postgres' ]

Write Object to YAML file in Node Javascript

  • Import fs and yaml modules into a code
  • Create a javascript object that holds the data to write to the yaml file
  • Convert the object into yaml format using yaml.dump() function
  • Finally, write the yaml format data into a file using the fs.writeFileSync() function

This example shows javascript object is serialized into YAML format.

const fs = require('fs');
const yaml = require('js-yaml');

const data = {
    author: 'Franc',
    database: {
        driver: "com.mysql.jdbc.Driver",
        port: 3306,
        dbname: "students",
        username: "root",
        password: "root"
    },
    support: ['mysql', 'mongodb', 'postgres']
};

const yamlString = yaml.dump(data);

fs.writeFileSync('result.yaml', yamlString, 'utf8');

And the result.yaml file created with the below content

author: Franc
database:
  driver: com.mysql.jdbc.Driver
  port: 3306
  dbname: students
  username: root
  password: root
support:
  - mysql
  - MongoDB
  - Postgres