New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

websocket-as-promised

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

websocket-as-promised

Promise-based WebSocket client

  • 0.5.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.1K
decreased by-56.9%
Maintainers
1
Weekly downloads
 
Created
Source

websocket-as-promised

Build Status npm license

Promise-based W3C WebSocket client

A WebSocket client library that allows to use Promises for connecting, disconnecting and messaging with server.

Installation

npm install websocket-as-promised --save

Usage in browser

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'));

Usage in Node.js

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'));

Messaging

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

API

Classes

WebSocketAsPromised

Typedefs

Options : Object

WebSocketAsPromised

Kind: global class

new WebSocketAsPromised(url, [options])

Constructor. Unlike original WebSocket it does not immediately open connection. Please call open() method manually to connect.

ParamTypeDescription
urlStringWebSocket URL
[options]Options

wsp.ws ⇒ WebSocket

Returns original WebSocket instance created by options.createWebSocket.

Kind: instance property of WebSocketAsPromised

wsp.isOpening ⇒ Boolean

Is WebSocket connection in opening state.

Kind: instance property of WebSocketAsPromised

wsp.isOpened ⇒ Boolean

Is WebSocket connection opened.

Kind: instance property of WebSocketAsPromised

wsp.isClosing ⇒ Boolean

Is WebSocket connection in closing state.

Kind: instance property of WebSocketAsPromised

wsp.isClosed ⇒ Boolean

Is WebSocket connection closed.

Kind: instance property of WebSocketAsPromised

wsp.onMessage ⇒ Channel

Event channel triggered every time when message from server arrives. Listener accepts two arguments:

  1. jsonData if JSON parse succeeded
  2. original event.data

Kind: instance property of WebSocketAsPromised
See: https://vitalets.github.io/chnl/#channel
Example

wsp.onMessage.addListener((data, jsonData) => console.log(data, jsonData));

wsp.onClose ⇒ 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

wsp.open() ⇒ Promise

Opens WebSocket connection.

Kind: instance method of WebSocketAsPromised

wsp.request(data, [options]) ⇒ Promise

Performs request and waits for response.

Kind: instance method of WebSocketAsPromised

ParamTypeDefault
dataObject
[options]Object
[options.requestId]String | Number<auto-generated>
[options.requestIdPrefix]String""
[options.timeout]Number0

wsp.send(data)

Sends any data by WebSocket.

Kind: instance method of WebSocketAsPromised

ParamType
dataString | ArrayBuffer | Blob

wsp.close() ⇒ Promise

Closes WebSocket connection.

Kind: instance method of WebSocketAsPromised

Options : Object

Kind: global typedef
Defaults: please see options.js for default values
Properties

NameTypeDefaultDescription
createWebSocketfunctioncustom WebSocket creation function
packRequestfunctioncustom packing request function
unpackResponsefunctioncustom unpacking response function
timeoutNumber0timeout for opening connection and sending messages
connectionTimeoutNumber0special timeout for opening connection (defaults to timeout)

License

MIT @ Vitaliy Potapov

Keywords

FAQs

Package last updated on 11 Oct 2017

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc