TenDRILLL
TenDRILLL

Reputation: 241

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.

Upvotes: 10

Views: 20516

Answers (2)

nima
nima

Reputation: 95

You can use yaml.dump() function with some optional configurations:

try {
    const file = path.resolve(__dirname, `./config/`, CONFIG.yml)

    const fileContents = fs.readFileSync(file, 'utf8');
    const baseConfig = yaml.load(fileContents);

    // change the baseConfig file to whatever you want...

    const newYaml = yaml.dump(baseConfig, {
        lineWidth: -1, // Ensure no line
        noRefs: true, // Avoid unnecessary references in the output
        condenseFlow: true // Prevent multi-line block scalars
    });

    fs.writeFileSync(configFile, newYaml, 'utf8');
    console.log(`Configuration updated successfully: ${configFile}`);
} catch (e) {
    console.error(`Error loading or updating config file ${configFile}:`, e);
}

Upvotes: 0

TenDRILLL
TenDRILLL

Reputation: 241

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);
    }
});

Upvotes: 14

Related Questions