Created
November 11, 2015 03:19
-
-
Save davidtheclark/bbe416b0990337986929 to your computer and use it in GitHub Desktop.
Revisions
-
davidtheclark created this gist
Nov 11, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ 'use strict'; var fs = require('graceful-fs'); var Promise = require('pinkie-promise'); var yaml = require('js-yaml'); var parseJson = require('parse-json'); var requireFromString = require('require-from-string'); module.exports = function(configPath, configFormat) { return new Promise(function(resolve) { fs.readFile(configPath, 'utf8', function(err, content) { if (err) throw err; var parsedConfig = (function() { switch (configFormat) { case 'json': return parseJson(content); case 'yaml': return yaml.safeLoad(content); case 'js': return requireFromString(content); default: return tryAllParsing(content); } })(); if (!parsedConfig) { throw new Error( 'Failed to parse "' + configPath + '" as JSON, JS, or YAML.' ); } resolve({ config: parsedConfig, filepath: configPath, }); }); }); }; function tryAllParsing(content) { return tryParsing(content, parseJson, function() { return tryParsing(content, yaml.safeLoad, function() { return tryParsing(content, requireFromString, function() { return null; }); }); }); } function tryParsing(content, parser, cb) { try { return parser(content); } catch (e) { return cb(); } }