Security News
38% of CISOs Fear They’re Not Moving Fast Enough on AI
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
websocket-stream
Advanced tools
Use websockets with the node streams API. Works in browser and node
The websocket-stream npm package allows you to use WebSockets as a streaming interface in Node.js. It integrates WebSockets with the Node.js stream API, making it easier to work with real-time data streams over WebSocket connections.
Creating a WebSocket Stream Server
This code sets up an HTTP server and attaches a WebSocket stream server to it. The WebSocket server listens for incoming connections and echoes back any data it receives.
const websocket = require('websocket-stream');
const http = require('http');
const server = http.createServer();
const wss = websocket.createServer({ server }, function(stream) {
stream.pipe(stream); // Echoes back the received data
});
server.listen(8080, () => {
console.log('WebSocket server is listening on port 8080');
});
Connecting to a WebSocket Stream Server
This code demonstrates how to connect to a WebSocket stream server and send data to it. It also listens for data from the server and logs it to the console.
const websocket = require('websocket-stream');
const stream = websocket('ws://localhost:8080');
stream.write('Hello, server!');
stream.on('data', function(data) {
console.log('Received:', data.toString());
});
Using WebSocket Streams with Node.js Streams
This code shows how to pipe a file stream to a WebSocket stream. It reads data from a file and sends it over the WebSocket connection.
const websocket = require('websocket-stream');
const fs = require('fs');
const stream = websocket('ws://localhost:8080');
const fileStream = fs.createReadStream('example.txt');
fileStream.pipe(stream);
The 'ws' package is a popular WebSocket implementation for Node.js. It provides a comprehensive set of features for working with WebSockets, including support for both client and server. Unlike websocket-stream, 'ws' does not integrate directly with the Node.js stream API, but it offers more control over WebSocket connections and is widely used in the community.
The 'socket.io' package is a real-time communication library that provides both WebSocket and fallback support for other transport protocols. It is designed for building real-time applications and offers features like rooms, namespaces, and broadcasting. While it is more feature-rich than websocket-stream, it is also more complex and may be overkill for simple WebSocket streaming use cases.
The 'websocket' package is another WebSocket implementation for Node.js. It supports both client and server and provides a simple API for working with WebSocket connections. It does not integrate with the Node.js stream API like websocket-stream, but it is a solid choice for basic WebSocket functionality.
Use HTML5 websockets using the Node Streams API.
This module works in Node or in Browsers that support WebSockets. You can use browserify to package this module for browser use.
var websocket = require('websocket-stream')
var ws = websocket('ws://echo.websocket.org')
process.stdin.pipe(ws)
ws.pipe(process.stdout)
In the example above ws
is a duplex stream. That means you can pipe output to anything that accepts streams. You can also pipe data into streams (such as a webcam feed or audio data).
The underlying WebSocket
instance is available as ws.socket
.
The available options differs depending on if you use this module in the browser or with node.js. Options can be passed in as the third or second argument - WebSocket(address, [protocols], [options])
.
options.browserBufferSize
How much to allow the socket.bufferedAmount to grow before starting to throttle writes. This option has no effect in node.js.
Default: 1024 * 512
(512KiB)
options.browserBufferTimeout
How long to wait before checking if the socket buffer has drained sufficently for another write. This option has no effect in node.js.
Default: 1000
(1 second)
options.objectMode
Send each chunk on its own, and do not try to pack them in a single websocket frame.
Default: false
options.binary
Always convert to Buffer
in Node.js before sending.
Forces options.objectMode
to false
.
Default: true
options.perMessageDeflate
We recommend disabling the per message deflate extension to achieve the best throughput.
Default: true
on the client, false
on the server.
Example:
var websocket = require('websocket-stream')
var ws = websocket('ws://realtimecats.com', {
perMessageDeflate: false
})
Beware that this option is ignored by browser clients. To make sure that permessage-deflate is never used, disable it on the server.
When used in node.js see the ws.WebSocket documentation
Using the ws
module you can make a websocket server and use this module to get websocket streams on the server:
var websocket = require('websocket-stream')
var wss = websocket.createServer({server: someHTTPServer}, handle)
function handle(stream, request) {
// `request` is the upgrade request sent by the client.
fs.createReadStream('bigdata.json').pipe(stream)
}
We recommend disabling the per message deflate extension to achieve the best throughput:
var websocket = require('websocket-stream')
var wss = websocket.createServer({
perMessageDeflate: false,
server: someHTTPServer
}, handle)
function handle(stream) {
fs.createReadStream('bigdata.json').pipe(stream)
}
You can even use it on express.js with the express-ws library:
const express = require('express');
const expressWebSocket = require('express-ws');
const websocketStream = require('websocket-stream/stream');
const app = express();
// extend express app with app.ws()
expressWebSocket(app, null, {
// ws options here
perMessageDeflate: false,
});
app.ws('/bigdata.json', function(ws, req) {
// convert ws instance to stream
const stream = websocketStream(ws, {
// websocket-stream options here
binary: true,
});
fs.createReadStream('bigdata.json').pipe(stream);
});
app.listen(3000);
npm test
First start the echo server by running node test-server.js
Then run npm start
and open localhost:9966
in your browser and open the Dev Tools console to see test output.
BSD LICENSE
FAQs
Use websockets with the node streams API. Works in browser and node
The npm package websocket-stream receives a total of 142,736 weekly downloads. As such, websocket-stream popularity was classified as popular.
We found that websocket-stream demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.
Security News
Company News
Socket is joining TC54 to help develop standards for software supply chain security, contributing to the evolution of SBOMs, CycloneDX, and Package URL specifications.