filesystem.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /**
  2. * Filesystem wrapper with promises
  3. *
  4. *
  5. */
  6. 'use strict';
  7. module.exports = function(Q, fs, path) {
  8. function exists(src) {
  9. var defer = Q.defer();
  10. fs.exists(src, function (exists) {
  11. if (!exists) {
  12. var err = new Error(src + 'does not exists');
  13. err.code = 'NEXIST';
  14. return defer.reject(err);
  15. }
  16. defer.resolve(exists);
  17. });
  18. return defer.promise;
  19. }
  20. function find(dir, pattern) {
  21. var defer = Q.defer();
  22. fs.readdir(dir, function (err, entries) {
  23. if (err) {
  24. return defer.reject(err);
  25. }
  26. var entry = entries.filter(pattern.test.bind(pattern))[0];
  27. if (!entry) {
  28. err = new Error('.xcodeproj cannot be found in ' + dir);
  29. err.code = 'NEXIST';
  30. return defer.reject(err);
  31. }
  32. defer.resolve(path.join(dir, entry));
  33. });
  34. return defer.promise;
  35. }
  36. function readFile(src) {
  37. var defer = Q.defer();
  38. fs.readFile(src, function (err, data) {
  39. if (err) {
  40. return defer.reject(err);
  41. }
  42. defer.resolve(data);
  43. });
  44. return defer.promise;
  45. }
  46. function writeFile(dest, content) {
  47. var defer = Q.defer();
  48. fs.writeFile(dest, content, function (err) {
  49. if (err) {
  50. return defer.reject(err);
  51. }
  52. defer.resolve();
  53. });
  54. return defer.promise;
  55. }
  56. function copy(src, dest) {
  57. return readFile(src).then(function(content) {
  58. return writeFile(dest, content);
  59. });
  60. }
  61. function unlink(dest) {
  62. var defer = Q.defer();
  63. fs.unlink(dest, function (err) {
  64. if (err) {
  65. return defer.reject(err);
  66. }
  67. defer.resolve();
  68. });
  69. return defer.promise;
  70. }
  71. function mkdir(dest) {
  72. var defer = Q.defer();
  73. fs.mkdir(dest, function (err) {
  74. if (err && err.code != 'EEXIST') {
  75. return defer.reject(err);
  76. }
  77. defer.resolve();
  78. });
  79. return defer.promise;
  80. }
  81. function rmdir(dest) {
  82. var defer = Q.defer();
  83. fs.rmdir(dest, function (err) {
  84. if (err) {
  85. return defer.reject(err);
  86. }
  87. defer.resolve();
  88. });
  89. return defer.promise;
  90. }
  91. return {
  92. exists: exists,
  93. find: find,
  94. readFile: readFile,
  95. writeFile: writeFile,
  96. copy: copy,
  97. unlink: unlink,
  98. mkdir: mkdir,
  99. rmdir: rmdir
  100. };
  101. };