development.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. const Wt = require('wt');
  3. const fs = require('fs');
  4. const Base = require('sdk-base');
  5. // only used by local dev enviroment
  6. class DevelopmentEventSource extends Base {
  7. constructor() {
  8. super();
  9. this.wt = new Wt({
  10. // check if the under-watch directory is still alive every minute
  11. rewatchInterval: 60000,
  12. })
  13. .on('all', (...args) => this._onWtChange(...args))
  14. .on('error', (...args) => this.emit('error', ...args));
  15. this._fileWatching = new Map();
  16. this.ready(true);
  17. }
  18. watch(path) {
  19. try {
  20. const stat = fs.statSync(path);
  21. if (stat.isFile(path)) {
  22. const handler = fs.watch(path, this._onFsWatchChange.bind(this, path));
  23. // 保存 handler,用于接触监听
  24. this._fileWatching.set(path, handler);
  25. } else if (stat.isDirectory()) {
  26. this.wt.watch(path);
  27. }
  28. } catch (e) {
  29. // file not exist, do nothing
  30. // do not emit error, in case of too many logs
  31. }
  32. }
  33. unwatch(path) {
  34. if (!path) return;
  35. const h = this._fileWatching.get(path);
  36. if (h) {
  37. // fs.watch 文件监听
  38. h.removeAllListeners();
  39. h.close();
  40. this._fileWatching.delete(path);
  41. } else {
  42. // wt 文件夹监听
  43. this.wt.unwatch(path);
  44. }
  45. }
  46. _onWtChange(info) {
  47. // debug('got %s, info %j', info.event, info);
  48. // { event: 'change',
  49. // path: '/Users/mk2/git/changing/test/fixtures/foo.js',
  50. // stat:
  51. // { dev: 16777220,
  52. // mode: 33188,
  53. // nlink: 1,
  54. // uid: 501,
  55. // gid: 20,
  56. // rdev: 0,
  57. // blksize: 4096,
  58. // ino: 72656587,
  59. // size: 11,
  60. // blocks: 8,
  61. // atime: Wed Jun 17 2015 00:08:11 GMT+0800 (CST),
  62. // mtime: Wed Jun 17 2015 00:08:38 GMT+0800 (CST),
  63. // ctime: Wed Jun 17 2015 00:08:38 GMT+0800 (CST),
  64. // birthtime: Tue Jun 16 2015 23:19:13 GMT+0800 (CST) } }
  65. this.emit('change', info);
  66. }
  67. _onFsWatchChange(path, event) {
  68. const info = {
  69. path,
  70. event,
  71. stat: fs.statSync(path),
  72. };
  73. // this.emit(info.event, info);
  74. this.emit('change', info);
  75. }
  76. }
  77. module.exports = DevelopmentEventSource;