@aptre/it-ws

中文文档
1.1.2发布于 2025/07/06Apache-2.0 OR MITTypeScriptES Module近 30 天下载 2.3万

Simple async iterables for websocket client connections

原始使用文档
文档目录16 节
  1. Notice: Fork
  2. Table of contents
  3. Install
  4. Usage
  5. Example - client
  6. Example - server
  7. API
  8. import { connect } from '@aptre/it-ws/client'
  9. import { createServer } from '@aptre/it-ws/server'
  10. use with an http server
  11. core, websocket wrapping functions
  12. import duplex from '@aptre/it-ws/duplex'
  13. import sink from '@aptre/it-ws/sink'
  14. import source from '@aptre/it-ws/source'
  15. License
  16. Contribution

it-ws

Simple async iterables for websocket client connections

Notice: Fork

This is a maintenance fork of it-ws. It minimizes dependencies when compared to the upstream package.

This package is published at @aptre/it-ws.

Table of contents

Install

$ npm i @aptre/it-ws

Usage

Example - client

import { connect } from '@aptre/it-ws/client'
import { pipe } from 'it-pipe'

const stream = connect(WS_URL)

await stream.connected() // Wait for websocket to be connected (optional)

pipe(source, stream, sink)

Example - server

import { createServer } from '@aptre/it-ws/server'
import { pipe } from 'it-pipe'

const server = createServer(stream => {
  //pipe the stream somewhere.
  //eg, echo server
  pipe(stream, stream)
})

await server.listen(PORT)

API

import { connect } from '@aptre/it-ws/client'

connect(url, { binary: boolean })

Create a websocket client connection. Set binary: true to get a stream of arrayBuffers (on the browser). Defaults to true on node, but to strings on the browser. This may cause a problems if your application assumes binary.

For adding options to the WebSocket instance, as websockets/ws/blob/master/doc/ws.md#new-websocketaddress-protocols-options, you can provide an object with the websocket property into the connect options.

const stream = connect(url)
// stream is duplex and is both a `source` and `sink`.
// See this for more information:
// https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#duplex-it

import { createServer } from '@aptre/it-ws/server'

Create async iterable websocket servers.

createServer(options?, onConnection)

options takes the same server options as ws module

onConnection(stream) is called every time a connection is received.

Example

One duplex service you may want to use this with is muxrpc

import { createServer } from '@aptre/it-ws/server'
import { connect } from '@aptre/it-ws/client'
import { pipe } from 'it-pipe'

createServer({
  onConnection: (stream) => {
    // pipe duplex style to your service
    pipe(stream, service.createStream(), stream)
  }
})
.listen(9999)

const stream = client.createStream()

await pipe(
  stream,
  connect('ws://localhost:9999'),
  stream
)

if the connection fails, the stream will throw

try {
  await pipe(
    stream,
    connect('ws://localhost:9999'),
    stream
  )
} catch (err) {
  // handle err
}

To run the server over TLS:

createServer({
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
  // other options
})
.listen(9999)

To add client-authentication to the server, you can set verifyClient. Documentation here.

function verifyClient (info) {
  return info.secure == true
}
createServer({
  verifyClient: verifyClient
  // other options
})

use with an http server

if you have an http server that you also need to serve stuff over, and want to use a single port, use the server option.

import http from 'http'

const server = http.createServer(function(req, res){...}).listen(....)

createServer({
  server: server
  // other options
})

core, websocket wrapping functions

these modules are used internally, to wrap a websocket. you probably won't need to touch these, but they are documented anyway.

import duplex from '@aptre/it-ws/duplex'

turn a websocket into a duplex stream. If provided, opts is passed to sink(socket, opts).

WebSockets do not support half open mode. see allowHalfOpen option in net module

If you have a protocol that assumes halfOpen connections, but are using a networking protocol like websockets that does not support it, I suggest using it-goodbye with your protocol.

The duplex stream will also contain a copy of the properties from the http request that became the websocket. they are method, url, headers and upgrade.

also exposed at: import { duplex } from '@aptre/it-ws'

import sink from '@aptre/it-ws/sink'

Create a Sink that will write data to the socket. opts may be {closeOnEnd: true, onClose: onClose}. onClose will be called when the sink ends. If closeOnEnd=false the stream will not close, it will just stop emitting data. (by default closeOnEnd is true)

If opts is a function, then onClose = opts; opts.closeOnEnd = true.

import sink from '@aptre/it-ws/sink'
import { pipe } from 'it-pipe'
import each from 'it-foreach'
import delay from 'delay'

// connect to the echo endpoint for test/server.js
var socket = new WebSocket('wss://echo.websocket.org')

// write values to the socket
pipe(
  async function * () {
    while (true) {
      yield 'hello @ ' + Date.now()
    }
  }(),
  // throttle so it doesn't go nuts
  (source) => each(source, () => delay(100))
  sink(socket)
);

socket.addEventListener('message', function(evt) {
  console.log('received: ' + evt.data);
});

also exposed at import { sink } from '@aptre/it-ws'

import source from '@aptre/it-ws/source'

Create a Source that will read data from the socket.

import { pipe } from 'it-pipe'
import source from '@aptre/it-ws/source'

pipe(
  // connect to the test/server.js endpoint
  source(new WebSocket('ws://localhost:3000/read')),
  async (source) => {
    for await (const buf of source) {
      console.info(buf)
    }
  }
);

also exposed at import { source } from '@aptre/it-ws'

License

Licensed under either of

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

版本与发布记录

@aptre/it-ws 共发布 3 个版本,首次发布于 2023/12/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.1.2latest2025/07/061.3 年前
1.0.12024/06/262 年前
1.0.02023/12/202 年前

关于 @aptre/it-ws 的常见问题

@aptre/it-ws 是什么?

Simple async iterables for websocket client connections

如何安装 @aptre/it-ws?

在项目目录运行 npm install @aptre/it-ws,或使用 pnpm add / yarn add / bun add。

@aptre/it-ws 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aptre/it-ws 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@aptre/it-ws 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aptre/it-ws 可以商用吗?

@aptre/it-ws 使用 Apache-2.0 OR MIT 许可。可在 Apache-2.0、MIT 中任选其一遵守。选择 Apache-2.0 时,宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aptre/it-ws 的下载量有多少?

根据 npm 官方下载统计,@aptre/it-ws 在 2026/10/07 – 2026/11/05 这 30 天内被下载 23,406 次,日均约 780 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aptre/it-ws 还在维护吗?

最新版本 1.1.2 发布于 2025/07/06(1.3 年前);至今共发布 3 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/12/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。