JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 8088
  • Score
    100M100P100Q136926F
  • License MIT

Promise-based WebSocket wrapper

Package Exports

  • websocket-as-promised

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (websocket-as-promised) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

websocket-as-promised

Build Status npm license

Promise-based W3C WebSocket wrapper

Installation

npm install websocket-as-promised --save

Usage in browser

const WebSocketAsPromised = require('websocket-as-promised');

const wsp = new WebSocketAsPromised();
wsp.open('ws://echo.websocket.org')
  .then(() => wsp.send({foo: 'bar'}))
  .then(response => console.log(response.id))
  .then(() => wsp.close())
  .catch(e => console.error(e));

Usage in Node.js

As there is no built-in WebSocket client in Node.js, you should use a third-party module. The most popular W3C compatible solution is websocket:

const W3CWebSocket = require('websocket').w3cwebsocket;
const WebSocketAsPromised = require('websocket-as-promised');

const wsp = new WebSocketAsPromised({WebSocket: W3CWebSocket});
wsp.open('ws://echo.websocket.org')
  .then(...)

API

new WebSocketAsPromised(options)

  /**
   * Constructor
   *
   * @param {Object} [options]
   * @param {String} [options.idProp="id"] id property name attached to each message
   * @param {Object} [options.timeout=0] default timeout for requests
   * @param {Object} [options.WebSocket=WebSocket] custom WebSocket constructor
   */

.open(url)

  /**
   * Open WebSocket connection
   *
   * @param {String} url
   * @returns {Promise}
   */

.request(data, options)

  /**
   * Performs request and resolves after response with corresponding `id`.
   *
   * @param {Object} data
   * @param {Object} [options]
   * @param {Number} [options.timeout]
   * @returns {Promise}
   */

.close()

  /**
   * Close WebSocket connection
   *
   * @returns {Promise}
   */

.onMessage

  /**
   * OnMessage channel with `.addListener` / `.removeListener` methods.
   * @see https://github.com/vitalets/chnl
   *
   * @returns {Channel}
   */

.ws

  /**
   * Returns raw WebSocket instance
   *
   * @returns {WebSocket}
   */

License

MIT @ Vitaliy Potapov