Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
websocket-as-promised
Advanced tools
Promise-based W3C WebSocket client
A WebSocket client library that allows to use Promises for connecting, disconnecting and messaging with server.
npm install websocket-as-promised --save
const WebSocketAsPromised = require('websocket-as-promised');
const wsp = new WebSocketAsPromised('ws://echo.websocket.org');
console.log('connecting...');
wsp.open()
.then(() => console.log('connected'))
.then(() => wsp.request({foo: 'bar'}))
.then(response => console.log('response message received', response))
.then(() => wsp.close())
.then(() => console.log('disconnected'));
As there is no built-in WebSocket client in Node.js, you should use a third-party module. For example websocket package:
const W3CWebSocket = require('websocket').w3cwebsocket;
const WebSocketAsPromised = require('websocket-as-promised');
const wsp = new WebSocketAsPromised('ws://echo.websocket.org', {
createWebSocket: url => new W3CWebSocket(url) // custom WebSocket constructor
});
console.log('connecting...');
wsp.open()
.then(() => console.log('connected'))
.then(() => wsp.request({foo: 'bar'}))
.then(response => console.log('response message received', response))
.then(() => wsp.close())
.then(() => console.log('disconnected'));
The .request()
method is used to send WebSocket message to the server and wait for the response.
Matching between request and response is performed by unique identifier requestId
that should present
in both incoming and outcoming message. By default, requestId
is auto-generated and attached to data
assuming you are sending JSON:
wsp.request({foo: 'bar'}) // actually sends {requestId: '12345', foo: 'bar'}
.then(response => console.log(response)); // waits response from server with the same requestId: {requestId: '12345', status: 'ok'}
You can set requestId
manually:
wsp.request({foo: 'bar'}, {requestId: '123'});
If you need full control over messaging you can use packRequest
/ unpackResponse
options.
For example, you can use custom property id
for unique request identifier:
const wsp = new WebSocketAsPromised(url, {
packRequest: (requestId, data) => {
data.id = requestId; // attach requestId as 'id'
return JSON.stringify(data);
},
unpackResponse: message => {
const data = JSON.parse(message);
return {requestId: data.id, data}; // read requestId from 'id' prop
}
});
wsp.open()
.then(() => wsp.request({foo: 'bar'}, {requestId: 1}));
Or send requests in binary format:
const wsp = new WebSocketAsPromised(url, {
packRequest: (requestId, data) => new Uint8Array([requestId, data]),
unpackResponse: message => {
const arr = new Uint8Array(message);
return {requestId: arr[0], data: arr[1]};
}
});
wsp.open()
.then(() => wsp.request(42));
Note:
If you want just send data and do not expect any response - use .send()
method:
wsp.send(JSON.stringify({foo: 'bar'})); // does not return promise
Object
Kind: global class
WebSocket
Boolean
Boolean
Boolean
Boolean
Channel
Channel
Promise
Promise
Promise
Constructor. Unlike original WebSocket it does not immediately open connection.
Please call open()
method manually to connect.
Param | Type | Description |
---|---|---|
url | String | WebSocket URL |
[options] | Options |
WebSocket
Returns original WebSocket instance created by options.createWebSocket
.
Kind: instance property of WebSocketAsPromised
Boolean
Is WebSocket connection in opening state.
Kind: instance property of WebSocketAsPromised
Boolean
Is WebSocket connection opened.
Kind: instance property of WebSocketAsPromised
Boolean
Is WebSocket connection in closing state.
Kind: instance property of WebSocketAsPromised
Boolean
Is WebSocket connection closed.
Kind: instance property of WebSocketAsPromised
Channel
Event channel triggered every time when message from server arrives. Listener accepts two arguments:
jsonData
if JSON parse succeededevent.data
Kind: instance property of WebSocketAsPromised
See: https://vitalets.github.io/chnl/#channel
Example
wsp.onMessage.addListener((data, jsonData) => console.log(data, jsonData));
Channel
Event channel triggered when connection closed.
Listener accepts single argument {code, reason}
.
Kind: instance property of WebSocketAsPromised
See: https://vitalets.github.io/chnl/#channel
Promise
Opens WebSocket connection.
Kind: instance method of WebSocketAsPromised
Promise
Performs request and waits for response.
Kind: instance method of WebSocketAsPromised
Param | Type | Default |
---|---|---|
data | Object | |
[options] | Object | |
[options.requestId] | String | Number | <auto-generated> |
[options.requestIdPrefix] | String | "" |
[options.timeout] | Number | 0 |
Sends any data by WebSocket.
Kind: instance method of WebSocketAsPromised
Param | Type |
---|---|
data | String | ArrayBuffer | Blob |
Promise
Closes WebSocket connection.
Kind: instance method of WebSocketAsPromised
Object
Kind: global typedef
Defaults: please see options.js
for default values
Properties
Name | Type | Default | Description |
---|---|---|---|
createWebSocket | function | custom WebSocket creation function | |
packRequest | function | custom packing request function | |
unpackResponse | function | custom unpacking response function | |
timeout | Number | 0 | timeout for opening connection and sending messages |
connectionTimeout | Number | 0 | special timeout for opening connection (defaults to timeout ) |
MIT @ Vitaliy Potapov
FAQs
A WebSocket client library providing Promise-based API for connecting, disconnecting and messaging with server
The npm package websocket-as-promised receives a total of 1,025 weekly downloads. As such, websocket-as-promised popularity was classified as popular.
We found that websocket-as-promised demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 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
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.