You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中能否创建互联Duplex流?用于Socket单元测试

实现互联Duplex流的方案

核心实现思路

创建两个Duplex实例,让它们互相作为对方的数据来源:当其中一端调用write()时,将数据推送到另一端的可读缓冲区;另一端调用read()就能取出这些数据,同时触发data事件。

具体代码实现

const { Duplex } = require('stream');

function createLinkedDuplexes() {
  let local, remote;

  // 创建本地端流
  local = new Duplex({
    read() {
      // 数据来自remote的write操作,无需主动生成数据
    },
    write(chunk, encoding, callback) {
      // 将本地写入的数据推送到remote的可读缓冲区
      remote.push(chunk, encoding);
      callback();
    },
    destroy(error, callback) {
      remote = null;
      callback(error);
    }
  });

  // 创建远程端流
  remote = new Duplex({
    read() {
      // 数据来自local的write操作,无需主动生成数据
    },
    write(chunk, encoding, callback) {
      // 将远程写入的数据推送到local的可读缓冲区
      local.push(chunk, encoding);
      callback();
    },
    destroy(error, callback) {
      local = null;
      callback(error);
    }
  });

  return [local, remote];
}

功能验证

按你期望的API测试:

const [local, remote] = createLinkedDuplexes();

local.write('abc');
console.log(remote.read().toString()); // 输出 'abc'

remote.write('def');
console.log(local.read().toString()); // 输出 'def'

Jest单元测试示例

监听data事件验证双向数据传输:

test('linked duplexes should transfer data bidirectionally', (done) => {
  const [local, remote] = createLinkedDuplexes();

  remote.on('data', (chunk) => {
    expect(chunk.toString()).toBe('test-local');
    remote.write('test-remote');
  });

  local.on('data', (chunk) => {
    expect(chunk.toString()).toBe('test-remote');
    done();
  });

  local.write('test-local');
});

补充说明

  • 若需传输对象而非Buffer/字符串,创建Duplex时添加objectMode: true选项即可。
  • 用完流后调用destroy()方法,避免内存泄漏,上述实现已在销毁钩子中清理互相引用。

内容的提问来源于stack exchange,提问作者0xLogN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:45:23