virtual-console.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. const { EventEmitter } = require("events");
  3. module.exports = class VirtualConsole extends EventEmitter {
  4. constructor() {
  5. super();
  6. this.on("error", () => {
  7. // If "error" event has no listeners,
  8. // EventEmitter throws an exception
  9. });
  10. }
  11. forwardTo(anyConsole, { jsdomErrors } = {}) {
  12. for (const method of Object.keys(anyConsole)) {
  13. if (typeof anyConsole[method] === "function") {
  14. function onMethodCall(...args) {
  15. anyConsole[method](...args);
  16. }
  17. this.on(method, onMethodCall);
  18. }
  19. }
  20. function forward(e) {
  21. if (e.type === "unhandled-exception") {
  22. anyConsole.error(e.cause.stack);
  23. } else {
  24. anyConsole.error(e.message);
  25. }
  26. }
  27. if (jsdomErrors === undefined) {
  28. this.on("jsdomError", forward);
  29. } else if (Array.isArray(jsdomErrors)) {
  30. this.on("jsdomError", e => {
  31. if (jsdomErrors.includes(e.type)) {
  32. forward(e);
  33. }
  34. });
  35. } else if (jsdomErrors !== "none") {
  36. throw new TypeError("Invalid jsdomErrors option");
  37. }
  38. return this;
  39. }
  40. };