UNPKG

sbp-utils-yml-to-json

Version:

Small repo which reads yaml file(s) from a directory and returns a json object

97 lines (88 loc) 2.9 kB
var fs = require('fs'); var _ = require('lodash'); var YAML = require('yamljs'); var Promise = require('bluebird'); /** * This utility function scans a given directory for YAML-files and combines them to a JSON object * @param {Object} settings A valid settingsobject with a path A valid sourcePath to read YML files from * @return {Object[] || String} A JSON object || A string to path */ var step = function(settings) { return { settings: settings || {}, run: run }; }; /** * This utility function scans a given directory for YAML-files and combines them to a JSON object * @param {Object} pipeline A valid pipeline object * @return {Object[] || String} A JSON object || A string to path */ function run(pipeline, settings) { settings = settings || {}; var _readPath = settings.readPath || './raw_files'; var _writePath = settings.writePath || pipeline.getOutputDirPath(); var _omitFile = settings.omitFile || false; var _setKey = settings.setKey || true; var _fileName = settings.fileName || 'collection'; return Promise .resolve() .then(readFiles(pipeline, _readPath)) .then(writeStream(pipeline, _writePath, _omitFile, _fileName, _setKey)); } function readFiles(pipeline, _readPath) { return function () { if (!fs.existsSync(_readPath)){ throw new Error('Could not find path to files to read'); } // get file list var fileList = fs.readdirSync(_readPath); var items = []; // loop over files _.forEach(fileList, function(file) { // only use .md files if((file.substr(file.length - 4) === '.yml') || (file.substr(file.length - 5) === '.yaml')) { try { var obj = YAML.load(_readPath + '/' + file); items.push(obj); } catch(err) { pipeline.addLog('VARNING! Kunde inte tolka filen ' + file + '. Hoppar över filen', 'error'); } } }); return items; }; } function writeStream(pipeline, _writePath, _omitFile, _fileName, _setKey) { return function (items) { if(!_omitFile) { // check if we have a directory to scan, else create it if (!fs.existsSync(_writePath)) { try { fs.mkdirSync(_writePath); } catch(err){ throw new Error('Could not create destination path to put files in ' + err.message); } } //Deafult write to workfolder try { var content = JSON.stringify(items, null, 2); pipeline.writeFile({ path: _writePath +'/' + _fileName + '.json', data: content, title: 'Lista - från JSON filer', description: 'Denna lista är genererad direkt från anvisad mapp med YAML-filer' }); } catch(err){ throw new Error('Could not write to file ' + err.message); } pipeline.setKey("YAMLToJSONResultPath", _writePath + '/' + _fileName + '.json'); } if(_setKey) { pipeline.setKey("YAMLToJSONResult", items); } return items; }; } module.exports.step = step; module.exports.run = run;