filemap.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // # Filemap
  3. //
  4. // Takes an array of filepaths or an object with filenames as it's keys,
  5. // loads all the files and returns an object with the filenames as keys and
  6. // filedata as the value.
  7. //
  8. var exists = require('fs').exists;
  9. var readfile = require('fs').readFile;
  10. module.exports = function (map, encoding, callback) {
  11. if (typeof encoding === 'function') {
  12. callback = encoding;
  13. encoding = null;
  14. }
  15. var i, len;
  16. if (Array.isArray(map)) {
  17. var tmp = {};
  18. for (i = 0, len = map.length; i < len; i++) {
  19. tmp[map[i]] = false;
  20. }
  21. map = tmp;
  22. }
  23. var properties = Object.getOwnPropertyNames(map);
  24. var result = {};
  25. function loadFile(path) {
  26. if (!path) {
  27. callback(result);
  28. return;
  29. }
  30. exists(path, function (exists) {
  31. if (!exists) {
  32. result[path] = false;
  33. loadFile(properties.shift());
  34. }
  35. else {
  36. readfile(path, encoding, function (err, data) {
  37. if (err) {
  38. result[path] = false;
  39. }
  40. else {
  41. result[path] = data;
  42. }
  43. loadFile(properties.shift());
  44. });
  45. }
  46. });
  47. }
  48. loadFile(properties.shift());
  49. };