readJson.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var path = require('path');
  2. var bowerJson = require('bower-json');
  3. var Q = require('q');
  4. // The valid options are the same as bower-json#readFile.
  5. // If the "assume" option is passed, it will be used if no json file was found
  6. // This promise is resolved with [json, deprecated, assumed]
  7. // - json: The read json
  8. // - deprecated: The deprecated filename being used or false otherwise
  9. // - assumed: True if a dummy json was returned if no json file was found, false otherwise
  10. function readJson(file, options) {
  11. options = options || {};
  12. // Read
  13. return Q.nfcall(bowerJson.read, file, options)
  14. .spread(function (json, jsonFile) {
  15. var deprecated;
  16. jsonFile = path.basename(jsonFile);
  17. deprecated = jsonFile === 'component.json' ? jsonFile : false;
  18. return [json, deprecated, false];
  19. }, function (err) {
  20. // No json file was found, assume one
  21. if (err.code === 'ENOENT' && options.assume) {
  22. return [bowerJson.parse(options.assume, options), false, true];
  23. }
  24. err.details = err.message;
  25. if (err.file) {
  26. err.message = 'Failed to read ' + err.file;
  27. err.data = { filename: err.file };
  28. } else {
  29. err.message = 'Failed to read json from ' + file;
  30. }
  31. throw err;
  32. });
  33. }
  34. module.exports = readJson;