The usual way for manipulating a YAML file in JavaScript is to convert it to JSON, modify the JSON and then convert JSON back to YAML. Unfortunately this process will remove any comment and can mess up the styling of the document.

const yamlString = `
  # my value
  value: 100
const json = YAML.load(yamlString);

// updating the value
json.value = 200;

// getting back the YAML. Comments are gone...
console.log(YAML.dump(json)); // => `value: 100`

This was a problem in number of projects that we were using YAML. We wanted to update some values in YAML files without loosing the formatting and comments.

I wrote the YAWN YAML library to solve this problem. YAWN YAML uses the Abstract Syntax Tree(AST) of a YAML document to rebuild the file structure upon changes. This makes it possible to change a value in the YAML document without loosing structure of the document.

Here is an example of how it works:

import YAWN from 'ywan-yaml';
let str = `
# my comment
value: 1 # the value is here!

let yawn = new YAWN(str);

yawn.json = {value: 2};

console.log(yawn.yaml); // =>
// # my comment
// value: 1 # the value is here!

Please note that you need to replace .json value of the yawn instance object. This is because the setter function is looking at the new JSON and reconstruct the YAML structure.

This library is heavily tested and can be used in browser and Node.js environments. Please file a bug if you found one.