Skip to content

Instantly share code, notes, and snippets.

@MiguelSavignano
Created May 28, 2021 02:17
Show Gist options
  • Save MiguelSavignano/7d545a7b26d04a1835becce31efc7b5c to your computer and use it in GitHub Desktop.
Save MiguelSavignano/7d545a7b26d04a1835becce31efc7b5c to your computer and use it in GitHub Desktop.
Read folders with multiple yaml files and parse in a single object-
// project
// --path
// ----config.yml
// --path2
// ----config.yml
// { project: { path: { config: object }, path2: { config: object } } }
const globby = require('globby');
const fs = require('fs');
const yaml = require('yaml');
const _ = require('lodash');
async function readYamlFiles(rules = ['**/*.yaml|*.yml']) {
const paths = await globby(rules);
return paths.reduce((memo, path) => {
try {
const split = path.replace(/(\.yaml|\.yml)/g, '').split("/")
const object = yaml.parseAllDocuments(fs.readFileSync(path, 'utf-8'))
const keys = split.join('.')
return _.set(memo, keys, object)
} catch(e) {
console.error(e)
return memo
}
}, {})
}
module.exports = { readYamlFiles }
readYamlFiles().then(result => {
fs.writeFileSync("data.json", JSON.stringify(result, null, 2))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment