8

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.

Anthon
  • 69,918
  • 32
  • 186
  • 246
TenDRILLL
  • 201
  • 1
  • 3
  • 8
  • 2
    According to the documentation of *yamljs* this is not possible. You might have a look at other libraries. [*js-yaml*](https://github.com/nodeca/js-yaml) looks it is doing both (but the repos doesnt seems maintained, yet there are a lot of DLs on NPM). – Léopold Houdin Oct 02 '18 at 21:19
  • 1
    1) It is YAML, not YML, and the file extension/suffix for those files should be `.yaml` unless your filesystem does not support that. 2) Most YAML parsers/loaders drop meaninful information such as comments, ids doing such round tripping (load-modify-save), the only exeption that I know of is my Python based `ruamel.yaml`. – Anthon Oct 03 '18 at 03:07
  • I'll give the js-yaml a shot, thanks :3 – TenDRILLL Oct 03 '18 at 08:43
  • @TenDRILLL Were you able to write to yaml using js-yaml? – Nitish Bhardwaj Feb 20 '19 at 07:45
  • Yes I was, I just don't know how to close this lmao. – TenDRILLL Mar 05 '19 at 16:20
  • Nvm I answered it myself :D Marking it as the correct answer and closing this. – TenDRILLL Mar 05 '19 at 16:26

1 Answers1

12

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);
    }
});
TenDRILLL
  • 201
  • 1
  • 3
  • 8
  • what do you have into Settings.yml? And what into newGreet? – Salvatore Di Fazio Apr 27 '19 at 04:58
  • Why do you ask? newGreet is a local variable defined by the function, and my Settings.yml's structure had it like in my example for it. Obviously you cannot copypaste it, but it shows the basic idea on how to use it. – TenDRILLL Apr 29 '19 at 23:05