【问题标题】:Read value logged to the console in Deno在 Deno 中读取记录到控制台的值
【发布时间】:2026-01-31 11:15:02
【问题描述】:

如何在 Deno 中读取记录到控制台的值?我正在尝试编写一个测试来检查函数是否将正确的值记录到控制台。

我已经尝试过了,但它只能读取手动输入标准输入的值。 Getting values from Deno stdin

【问题讨论】:

    标签: javascript typescript console deno


    【解决方案1】:

    这更像是一种黑客攻击,但在我的情况下有效

    class BinarySearchTree<T> {
    // ...
    inOrderPrint() {
        if (this.left) {
          this.left.inOrderPrint();
        }
        console.log(this.value);
        if (this.right) {
          this.right.inOrderPrint();
        }
      }
    // ...
    }
    
    
    test("BST: should print elements in order", () => {
      let a = [];
      const log = console.log;
      console.log = x => {
        a.push(x);
      };
      const bst = new BinarySearchTree<number>(1);
      bst.insert(8);
      bst.insert(5);
      bst.insert(7);
      bst.insert(6);
      bst.insert(3);
      bst.insert(4);
      bst.insert(2);
      bst.inOrderPrint();
      console.log = log;
      assertEquals(a.join(""), "12345678");
    });

    【讨论】:

    • 这是一个有效的解决方案。另一种可能的捕获方法是覆盖所有console 操作在内部使用的Deno.core.print。不幸的是,覆盖Deno.stdout 将不起作用,因为Deno.core.print 目前独立于Deno.stdout