WebSocket Stream Adapter

5.5.2 · active · verified Sun Apr 19

websocket-stream provides an interface to WebSockets using the Node.js Streams API, allowing developers to pipe data directly to and from a WebSocket connection. It is designed to work seamlessly in both Node.js environments and modern browsers that support WebSockets, making it a versatile tool for real-time applications. The current stable version is 5.5.2, with minor and patch releases occurring periodically, indicating active maintenance. Key differentiators include its adherence to the Node.js Streams API for managing WebSocket data, offering a familiar and composable interface compared to directly manipulating `WebSocket` instances. It integrates well with server-side WebSocket libraries like `ws` and can be used with frameworks such as Express via `express-ws`, streamlining the creation of full-duplex communication channels.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic client-side usage, piping standard input to a WebSocket and piping received data to standard output, highlighting its duplex stream capabilities.

import websocket from 'websocket-stream';
import { createReadStream, createWriteStream } from 'fs';

const ws = websocket('ws://echo.websocket.org');

// Pipe stdin to the WebSocket
process.stdin.pipe(ws);

// Pipe WebSocket data to stdout
ws.pipe(process.stdout);

// Example of piping a file to the WebSocket
// const fileStream = createReadStream('data.txt');
// fileStream.pipe(ws);

// Example of receiving data from WebSocket and saving to a file
// const outputFileStream = createWriteStream('received.txt');
// ws.pipe(outputFileStream);

console.log('Connected to ws://echo.websocket.org. Type something and press Enter!');

view raw JSON →