In this post will be writing a thing or two about js-yaml as a means of parsing a YAML file into an object that you can then use to soft code you node.js application.
So for starters we need to work out just a basic YAML file example that has some foo bar like settings. An example that just has a single key value pair, and then maybe some nested key value pairs maybe.
So then lets first start with a basic YAML file example such as this:
As you can see the number sign can be used to indicate a comment. I started off by making a comment that informs someone looking over my simple configuration file that a user name value can be changed by changing the value for the user name key in this file.
I am also defining a object called options by just using a line break followed by whitespace indentation with spaces and not tabs. The white space indentation is what is used to inform a parser that the values are object keys of the current object.
So I saved this example as config.yaml, and now I just need a way to parse it into a workable object in node. To do this I will need a parser, I could make my own but why do that whne I can save a whole lot of time by using js-yaml.
So start a new node.js test project cd into the folder of it as usual and the add js-yaml to the project.
Once you have js-yaml in your node_modules folder working with it is pretty straight forward. The safe load method is the usual way to go about loading in some yaml, but first I need to get that yaml code. The built in nodejs file system module is one way to go about doing so.
In this post I will not be going over the full scope of YAML, there are some good resources that do just that. This is just another quick post of mine on one of the many node.js packages I have fiddled around with.
Be sure to check out my many other posts on node.js and npm packages.