all files / lib/strategy/ LoadFileConfigStrategy.js

97.3% Statements 36/37
90% Branches 18/20
100% Functions 5/5
97.3% Lines 36/37
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72                                                                       
'use strict';
 
var fs = require('fs');
var path = require('path');
var extend = require('../helpers/clone-extend').extend;
var parsers = require('./../parser');
var expandHomeDir = require('../helpers/expand-home-dir');
 
/**
 * Load File Config Strategy
 * Represents a strategy that loads configuration from either a JSON or YAML file into the configuration.
 * @constructor
 */
function LoadFileConfigStrategy (filePath, mustExist, encoding) {
  this.filePath = filePath;
  this.mustExist = mustExist || false;
  this.encoding = encoding || 'utf8';
}
 
LoadFileConfigStrategy.prototype.process = function (config, callback) {
  var outerScope = this;
 
  var mustExist = this.mustExist;
  var originalFilePath = this.filePath;
  var expandedFilePath = expandHomeDir(originalFilePath);
 
  // In case we don't have a home path but specified a '~' in our path...
  if (expandedFilePath === false) {
    if (mustExist) {
      return callback(new Error("Unable to load '" + originalFilePath + "'. Environment home not set."));
    }
    return callback(null, config);
  }
 
  var extension = path.extname(expandedFilePath).substring(1);
  var parser = parsers[extension];
 
  if (!parser) {
    return callback(new Error("Unable to load file '" + originalFilePath + "'. Extension '" + extension + "' not supported."));
  }
 
  fs.exists(expandedFilePath, function (exists) {
    if (!exists) {
      if (mustExist) {
        callback(new Error("Config file '" + originalFilePath + "' doesn't exist."));
      } else {
        callback(null, config);
      }
    } else {
      fs.readFile(expandedFilePath, { encoding: outerScope.encoding }, function (err, result) {
        Iif (err) {
          return callback(err);
        }
 
        parser(result, function (err, data) {
          if (err) {
            return callback(new Error("Error parsing file '" + expandedFilePath + "'.\nDetails: " + err));
          }
 
          Eif (data) {
            extend(config, data);
          }
 
          callback(null, config);
        });
      });
    }
  });
};
 
module.exports = LoadFileConfigStrategy;