debugger.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { SystemExternal } from './system_external.js';
  2. export class Debugger {
  3. static getInstance() {
  4. Debugger.instance = Debugger.instance || new Debugger();
  5. return Debugger.instance;
  6. }
  7. init(opt_file) {
  8. if (opt_file) {
  9. this.startDebugFile_(opt_file);
  10. }
  11. this.isActive_ = true;
  12. return this.fileHandle;
  13. }
  14. output(...args) {
  15. if (this.isActive_) {
  16. this.output_(args);
  17. }
  18. }
  19. generateOutput(func) {
  20. if (this.isActive_) {
  21. this.output_(func.apply(func, []));
  22. }
  23. }
  24. exit(callback = () => { }) {
  25. this.fileHandle.then(() => {
  26. if (this.isActive_ && this.stream_) {
  27. this.stream_.end('', '', callback);
  28. }
  29. });
  30. }
  31. constructor() {
  32. this.isActive_ = false;
  33. this.outputFunction_ = console.info;
  34. this.fileHandle = Promise.resolve();
  35. this.stream_ = null;
  36. }
  37. startDebugFile_(filename) {
  38. this.fileHandle = SystemExternal.fs.promises.open(filename, 'w');
  39. this.fileHandle = this.fileHandle.then((handle) => {
  40. this.stream_ = handle.createWriteStream(filename);
  41. this.outputFunction_ = function (...args) {
  42. this.stream_.write(args.join(' '));
  43. this.stream_.write('\n');
  44. }.bind(this);
  45. this.stream_.on('error', function (_error) {
  46. console.info('Invalid log file. Debug information sent to console.');
  47. this.outputFunction_ = console.info;
  48. }.bind(this));
  49. this.stream_.on('finish', function () {
  50. console.info('Finalizing debug file.');
  51. });
  52. });
  53. }
  54. output_(outputList) {
  55. if (console.info === this.outputFunction_) {
  56. this.outputFunction_.apply(console, ['Speech Rule Engine Debugger:'].concat(outputList));
  57. return;
  58. }
  59. this.fileHandle.then(() => this.outputFunction_.apply(this.outputFunction_, ['Speech Rule Engine Debugger:'].concat(outputList)));
  60. }
  61. }