index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var events = require('events');
  3. var path = require('path');
  4. var util = require('util');
  5. var vinylFile = require('vinyl-file');
  6. var File = require('vinyl');
  7. var through = require('through2');
  8. exports.create = function () {
  9. var store = {};
  10. function load(filepath) {
  11. var file;
  12. try {
  13. file = vinylFile.readSync(filepath);
  14. } catch (err) {
  15. file = new File({
  16. cwd: process.cwd(),
  17. base: process.cwd(),
  18. path: filepath,
  19. contents: null
  20. });
  21. }
  22. store[filepath] = file;
  23. return file;
  24. }
  25. var Store = function () {
  26. events.EventEmitter.apply(this, arguments);
  27. };
  28. util.inherits(Store, events.EventEmitter);
  29. Store.prototype.get = function (filepath) {
  30. filepath = path.resolve(filepath);
  31. return store[filepath] || load(filepath);
  32. };
  33. Store.prototype.add = function (file) {
  34. store[file.path] = file;
  35. this.emit('change');
  36. return this;
  37. };
  38. Store.prototype.each = function (onEach) {
  39. Object.keys(store).forEach(function (key, index) {
  40. onEach(store[key], index);
  41. });
  42. return this;
  43. };
  44. Store.prototype.stream = function () {
  45. var stream = through.obj();
  46. setImmediate(function () {
  47. this.each(stream.write.bind(stream));
  48. stream.end();
  49. }.bind(this));
  50. return stream;
  51. };
  52. return new Store();
  53. };