MemoryFileSystem.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var normalize = require("./normalize");
  6. var errors = require("errno");
  7. var stream = require("readable-stream");
  8. var ReadableStream = stream.Readable;
  9. var WritableStream = stream.Writable;
  10. function MemoryFileSystemError(err, path) {
  11. Error.call(this)
  12. if (Error.captureStackTrace)
  13. Error.captureStackTrace(this, arguments.callee)
  14. this.code = err.code;
  15. this.errno = err.errno;
  16. this.message = err.description;
  17. this.path = path;
  18. }
  19. MemoryFileSystemError.prototype = new Error();
  20. function MemoryFileSystem(data) {
  21. this.data = data || {};
  22. }
  23. module.exports = MemoryFileSystem;
  24. function isDir(item) {
  25. if(typeof item !== "object") return false;
  26. return item[""] === true;
  27. }
  28. function isFile(item) {
  29. if(typeof item !== "object") return false;
  30. return !item[""];
  31. }
  32. function pathToArray(path) {
  33. path = normalize(path);
  34. var nix = /^\//.test(path);
  35. if(!nix) {
  36. if(!/^[A-Za-z]:/.test(path)) {
  37. throw new MemoryFileSystemError(errors.code.EINVAL, path);
  38. }
  39. path = path.replace(/[\\\/]+/g, "\\"); // multi slashs
  40. path = path.split(/[\\\/]/);
  41. path[0] = path[0].toUpperCase();
  42. } else {
  43. path = path.replace(/\/+/g, "/"); // multi slashs
  44. path = path.substr(1).split("/");
  45. }
  46. if(!path[path.length-1]) path.pop();
  47. return path;
  48. }
  49. function trueFn() { return true; }
  50. function falseFn() { return false; }
  51. MemoryFileSystem.prototype.meta = function(_path) {
  52. var path = pathToArray(_path);
  53. var current = this.data;
  54. for(var i = 0; i < path.length - 1; i++) {
  55. if(!isDir(current[path[i]]))
  56. return;
  57. current = current[path[i]];
  58. }
  59. return current[path[i]];
  60. }
  61. MemoryFileSystem.prototype.existsSync = function(_path) {
  62. return !!this.meta(_path);
  63. }
  64. MemoryFileSystem.prototype.statSync = function(_path) {
  65. var current = this.meta(_path);
  66. if(_path === "/" || isDir(current)) {
  67. return {
  68. isFile: falseFn,
  69. isDirectory: trueFn,
  70. isBlockDevice: falseFn,
  71. isCharacterDevice: falseFn,
  72. isSymbolicLink: falseFn,
  73. isFIFO: falseFn,
  74. isSocket: falseFn
  75. };
  76. } else if(isFile(current)) {
  77. return {
  78. isFile: trueFn,
  79. isDirectory: falseFn,
  80. isBlockDevice: falseFn,
  81. isCharacterDevice: falseFn,
  82. isSymbolicLink: falseFn,
  83. isFIFO: falseFn,
  84. isSocket: falseFn
  85. };
  86. } else {
  87. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  88. }
  89. };
  90. MemoryFileSystem.prototype.readFileSync = function(_path, encoding) {
  91. var path = pathToArray(_path);
  92. var current = this.data;
  93. for(var i = 0; i < path.length - 1; i++) {
  94. if(!isDir(current[path[i]]))
  95. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  96. current = current[path[i]];
  97. }
  98. if(!isFile(current[path[i]])) {
  99. if(isDir(current[path[i]]))
  100. throw new MemoryFileSystemError(errors.code.EISDIR, _path);
  101. else
  102. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  103. }
  104. current = current[path[i]];
  105. return encoding ? current.toString(encoding) : current;
  106. };
  107. MemoryFileSystem.prototype.readdirSync = function(_path) {
  108. if(_path === "/") return Object.keys(this.data).filter(Boolean);
  109. var path = pathToArray(_path);
  110. var current = this.data;
  111. for(var i = 0; i < path.length - 1; i++) {
  112. if(!isDir(current[path[i]]))
  113. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  114. current = current[path[i]];
  115. }
  116. if(!isDir(current[path[i]])) {
  117. if(isFile(current[path[i]]))
  118. throw new MemoryFileSystemError(errors.code.ENOTDIR, _path);
  119. else
  120. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  121. }
  122. return Object.keys(current[path[i]]).filter(Boolean);
  123. };
  124. MemoryFileSystem.prototype.mkdirpSync = function(_path) {
  125. var path = pathToArray(_path);
  126. if(path.length === 0) return;
  127. var current = this.data;
  128. for(var i = 0; i < path.length; i++) {
  129. if(isFile(current[path[i]]))
  130. throw new MemoryFileSystemError(errors.code.ENOTDIR, _path);
  131. else if(!isDir(current[path[i]]))
  132. current[path[i]] = {"":true};
  133. current = current[path[i]];
  134. }
  135. return;
  136. };
  137. MemoryFileSystem.prototype.mkdirSync = function(_path) {
  138. var path = pathToArray(_path);
  139. if(path.length === 0) return;
  140. var current = this.data;
  141. for(var i = 0; i < path.length - 1; i++) {
  142. if(!isDir(current[path[i]]))
  143. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  144. current = current[path[i]];
  145. }
  146. if(isDir(current[path[i]]))
  147. throw new MemoryFileSystemError(errors.code.EEXIST, _path);
  148. else if(isFile(current[path[i]]))
  149. throw new MemoryFileSystemError(errors.code.ENOTDIR, _path);
  150. current[path[i]] = {"":true};
  151. return;
  152. };
  153. MemoryFileSystem.prototype._remove = function(_path, name, testFn) {
  154. var path = pathToArray(_path);
  155. if(path.length === 0) {
  156. throw new MemoryFileSystemError(errors.code.EPERM, _path);
  157. }
  158. var current = this.data;
  159. for(var i = 0; i < path.length - 1; i++) {
  160. if(!isDir(current[path[i]]))
  161. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  162. current = current[path[i]];
  163. }
  164. if(!testFn(current[path[i]]))
  165. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  166. delete current[path[i]];
  167. return;
  168. };
  169. MemoryFileSystem.prototype.rmdirSync = function(_path) {
  170. return this._remove(_path, "Directory", isDir);
  171. };
  172. MemoryFileSystem.prototype.unlinkSync = function(_path) {
  173. return this._remove(_path, "File", isFile);
  174. };
  175. MemoryFileSystem.prototype.readlinkSync = function(_path) {
  176. throw new MemoryFileSystemError(errors.code.ENOSYS, _path);
  177. };
  178. MemoryFileSystem.prototype.writeFileSync = function(_path, content, encoding) {
  179. if(!content && !encoding) throw new Error("No content");
  180. var path = pathToArray(_path);
  181. if(path.length === 0) {
  182. throw new MemoryFileSystemError(errors.code.EISDIR, _path);
  183. }
  184. var current = this.data;
  185. for(var i = 0; i < path.length - 1; i++) {
  186. if(!isDir(current[path[i]]))
  187. throw new MemoryFileSystemError(errors.code.ENOENT, _path);
  188. current = current[path[i]];
  189. }
  190. if(isDir(current[path[i]]))
  191. throw new MemoryFileSystemError(errors.code.EISDIR, _path);
  192. current[path[i]] = encoding || typeof content === "string" ? new Buffer(content, encoding) : content;
  193. return;
  194. };
  195. MemoryFileSystem.prototype.join = require("./join");
  196. MemoryFileSystem.prototype.pathToArray = pathToArray;
  197. MemoryFileSystem.prototype.normalize = normalize;
  198. // stream functions
  199. MemoryFileSystem.prototype.createReadStream = function(path, options) {
  200. var stream = new ReadableStream();
  201. var done = false;
  202. var data;
  203. try {
  204. data = this.readFileSync(path);
  205. } catch (e) {
  206. stream._read = function() {
  207. if (done) {
  208. return;
  209. }
  210. done = true;
  211. this.emit('error', e);
  212. this.push(null);
  213. };
  214. return stream;
  215. }
  216. options = options || { };
  217. options.start = options.start || 0;
  218. options.end = options.end || data.length;
  219. stream._read = function() {
  220. if (done) {
  221. return;
  222. }
  223. done = true;
  224. this.push(data.slice(options.start, options.end));
  225. this.push(null);
  226. };
  227. return stream;
  228. };
  229. MemoryFileSystem.prototype.createWriteStream = function(path, options) {
  230. var stream = new WritableStream(), self = this;
  231. try {
  232. // Zero the file and make sure it is writable
  233. this.writeFileSync(path, new Buffer(0));
  234. } catch(e) {
  235. // This or setImmediate?
  236. stream.once('prefinish', function() {
  237. stream.emit('error', e);
  238. });
  239. return stream;
  240. }
  241. var bl = [ ], len = 0;
  242. stream._write = function(chunk, encoding, callback) {
  243. bl.push(chunk);
  244. len += chunk.length;
  245. self.writeFile(path, Buffer.concat(bl, len), callback);
  246. }
  247. return stream;
  248. };
  249. // async functions
  250. ["stat", "readdir", "mkdirp", "rmdir", "unlink", "readlink"].forEach(function(fn) {
  251. MemoryFileSystem.prototype[fn] = function(path, callback) {
  252. try {
  253. var result = this[fn + "Sync"](path);
  254. } catch(e) {
  255. setImmediate(function() {
  256. callback(e);
  257. });
  258. return;
  259. }
  260. setImmediate(function() {
  261. callback(null, result);
  262. });
  263. };
  264. });
  265. ["mkdir", "readFile"].forEach(function(fn) {
  266. MemoryFileSystem.prototype[fn] = function(path, optArg, callback) {
  267. if(!callback) {
  268. callback = optArg;
  269. optArg = undefined;
  270. }
  271. try {
  272. var result = this[fn + "Sync"](path, optArg);
  273. } catch(e) {
  274. setImmediate(function() {
  275. callback(e);
  276. });
  277. return;
  278. }
  279. setImmediate(function() {
  280. callback(null, result);
  281. });
  282. };
  283. });
  284. MemoryFileSystem.prototype.exists = function(path, callback) {
  285. return callback(this.existsSync(path));
  286. }
  287. MemoryFileSystem.prototype.writeFile = function (path, content, encoding, callback) {
  288. if(!callback) {
  289. callback = encoding;
  290. encoding = undefined;
  291. }
  292. try {
  293. this.writeFileSync(path, content, encoding);
  294. } catch(e) {
  295. return callback(e);
  296. }
  297. return callback();
  298. };