Search code examples
node.jsmoduleyamlfile-writing

Node.js Writing into YAML file


I'm using Node.js and I'm having trouble figuring out how could I read a YAML file, replace a value in it, and write the updated value to the YAML file.

I'm currently using the module "yamljs" which allows me to load the YAML file and I've managed to edit the value in the loaded Object.

The only part I need help with, is how to write to the YAML file. Cause for some reason, I can't find the solution for that anywhere, and I'm not even sure if I could use the module for that.

The module does have some command line tools, but I'm not too sure how to use those either.


Solution

  • The module "js-yaml" worked for my case. https://github.com/nodeca/js-yaml

    Here's the code I used:

    const yaml = require('js-yaml');
    ...
    
    let doc = yaml.safeLoad(fs.readFileSync('./Settings.yml', 'utf8'));
    doc.General.Greeting = newGreet;
    fs.writeFile('./Settings.yml', yaml.safeDump(doc), (err) => {
        if (err) {
            console.log(err);
        }
    });