• Stars
    star
    595
  • Rank 75,217 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Promise-based API for WebSockets

websocket-as-promised

websocket-as-promised logo

Actions Status Known Vulnerabilities npm license

A WebSocket client library with Promise-based API for browser and Node.js.

Example

import WebSocketAsPromised from 'websocket-as-promised';

// create instance of WebSocket connection
const wsp = new WebSocketAsPromised('ws://example.com');

// wait for WebSocket connection to open
await wsp.open();

// send some data
wsp.send('data');

// wait for connection to close
await wsp.close();

Contents

Requirements

  • global Promise constructor

Installation

npm i websocket-as-promised --save

Usage in browser

import WebSocketAsPromised from 'websocket-as-promised';

const wsp = new WebSocketAsPromised('ws://example.com');

wsp.open()
  .then(() => wsp.send('message'))
  .then(() => wsp.close())
  .catch(e => console.error(e));

Or with ES7 async / await:

import WebSocketAsPromised from 'websocket-as-promised';

const wsp = new WebSocketAsPromised('ws://example.com');

(async () => {
  try {
    await wsp.open();
    wsp.send('message');
  } catch(e) {
    console.error(e);
  } finally {
    await wsp.close();
  }
})();

Usage in Node.js

As there is no built-in WebSocket client in Node.js, you should use a third-party WebSocket npm package.

Usage with websocket

Here you should use W3C compatible client - W3CWebSocket:

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

const wsp = new WebSocketAsPromised('ws://example.com', {
  createWebSocket: url => new W3CWebSocket(url)
});

wsp.open()
  .then(() => wsp.send('message'))
  .then(() => wsp.close())
  .catch(e => console.error(e));

Usage with ws

Here it is important to define extractMessageData option as event data are passed directly to onmessage handler, not as event.data by spec:

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

const wsp = new WebSocketAsPromised('ws://example.com', {
  createWebSocket: url => new WebSocket(url),
  extractMessageData: event => event, // <- this is important
});

wsp.open()
  .then(() => wsp.send('message'))
  .then(() => wsp.close())
  .catch(e => console.error(e));

Sending raw data

To send raw data use .send() method:

wsp.send('foo');

To handle raw data from server use .onMessage channel:

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

Sending JSON

To send JSON you should define packMessage / unpackMessage options:

const wsp = new WebSocketAsPromised(wsUrl, {
  packMessage: data => JSON.stringify(data),
  unpackMessage: data => JSON.parse(data)
});

To send data use .sendPacked() method passing json as parameter:

wsp.sendPacked({foo: 'bar'});

To read unpacked data from received message you can subscribe to onUnpackedMessage channel:

wsp.onUnpackedMessage.addListener(data => console.log(data.status));

Sending binary

Example of sending Uint8Array:

const wsp = new WebSocketAsPromised(wsUrl, {
    packMessage: data => (new Uint8Array(data)).buffer,
    unpackMessage: data => new Uint8Array(data),
});

wsp.open()
  .then(() => wsp.sendPacked([1, 2, 3]))
  .then(() => wsp.close())
  .catch(e => console.error(e));

Sending requests

websocket-as-promised provides simple request-response mechanism (JSON RPC). Method .sendRequest() sends message with unique requestId and returns promise. That promise get resolved when response message with the same requestId comes. For reading/setting requestId from/to message there are two functions defined in options attachRequestId / extractRequestId:

const wsp = new WebSocketAsPromised(wsUrl, {
  packMessage: data => JSON.stringify(data),
  unpackMessage: data => JSON.parse(data),
  attachRequestId: (data, requestId) => Object.assign({id: requestId}, data), // attach requestId to message as `id` field
  extractRequestId: data => data && data.id,                                  // read requestId from message `id` field
});

wsp.open()
 .then(() => wsp.sendRequest({foo: 'bar'})) // actually sends {foo: 'bar', id: 'xxx'}, because `attachRequestId` defined above
 .then(response => console.log(response));  // waits server message with corresponding requestId: {id: 'xxx', ...}

By default requestId value is auto-generated, but you can set it manually:

wsp.sendRequest({foo: 'bar'}, {requestId: 42});

Note: you should implement yourself attaching requestId on server side.

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 to connect.

Param Type Description
url String WebSocket URL
[options] Options

wsp.ws ⇒ WebSocket

Returns original WebSocket instance created by options.createWebSocket.

Kind: instance property of WebSocketAsPromised

wsp.url ⇒ String

Returns WebSocket url.

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.onOpen ⇒ Channel

Event channel triggered when connection is opened.

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

wsp.onOpen.addListener(() => console.log('Connection opened'));

wsp.onSend ⇒ Channel

Event channel triggered every time when message is sent to server.

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

wsp.onSend.addListener(data => console.log('Message sent', data));

wsp.onMessage ⇒ Channel

Event channel triggered every time when message received from server.

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

wsp.onMessage.addListener(message => console.log(message));

wsp.onUnpackedMessage ⇒ Channel

Event channel triggered every time when received message is successfully unpacked. For example, if you are using JSON transport, the listener will receive already JSON parsed data.

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

wsp.onUnpackedMessage.addListener(data => console.log(data.foo));

wsp.onResponse ⇒ Channel

Event channel triggered every time when response to some request comes. Received message considered a response if requestId is found in it.

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

wsp.onResponse.addListener(data => console.log(data));

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
Example

wsp.onClose.addListener(event => console.log(`Connections closed: ${event.reason}`));

wsp.onError ⇒ Channel

Event channel triggered when by Websocket 'error' event.

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

wsp.onError.addListener(event => console.error(event));

wsp.open() ⇒ Promise.<Event>

Opens WebSocket connection. If connection already opened, promise will be resolved with "open event".

Kind: instance method of WebSocketAsPromised

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

Performs request and waits for response.

Kind: instance method of WebSocketAsPromised

Param Type Default
data *
[options] Object
[options.requestId] String | Number <auto-generated>
[options.timeout] Number 0

wsp.sendPacked(data)

Packs data with options.packMessage and sends to the server.

Kind: instance method of WebSocketAsPromised

Param Type
data *

wsp.send(data)

Sends data without packing.

Kind: instance method of WebSocketAsPromised

Param Type
data String | Blob | ArrayBuffer

wsp.waitUnpackedMessage(predicate, [options]) ⇒ Promise

Waits for particular message to come.

Kind: instance method of WebSocketAsPromised

Param Type Default Description
predicate function function to check incoming message.
[options] Object
[options.timeout] Number 0
[options.timeoutError] Error

Example

const response = await wsp.waitUnpackedMessage(data => data && data.foo === 'bar');

wsp.close([code], [reason]) ⇒ Promise.<Event>

Closes WebSocket connection. If connection already closed, promise will be resolved with "close event".

Kind: instance method of WebSocketAsPromised

Param Type Default Description
[code] number 1000 A numeric value indicating the status code.
[reason] string A human-readable reason for closing connection.

wsp.removeAllListeners()

Removes all listeners from WSP instance. Useful for cleanup.

Kind: instance method of WebSocketAsPromised

Options : Object

Kind: global typedef
Defaults: please see options.js
Properties

Name Type Default Description
[createWebSocket] function url => new WebSocket(url) custom function for WebSocket construction.
[packMessage] function noop packs message for sending. For example, data => JSON.stringify(data).
[unpackMessage] function noop unpacks received message. For example, data => JSON.parse(data).
[attachRequestId] function noop injects request id into data. For example, (data, requestId) => Object.assign({requestId}, data).
[extractRequestId] function noop extracts request id from received data. For example, data => data.requestId.
[extractMessageData] function event => event.data extracts data from event object.
timeout Number 0 timeout for opening connection and sending messages.
connectionTimeout Number 0 special timeout for opening connection, by default equals to timeout.

Changelog

Please see CHANGELOG.md.

License

MIT @ Vitaliy Potapov

* * *
If you love ❤️ JavaScript and would like to track new trending repositories,
have a look on vitalets/github-trending-repos.

More Repositories

1

x-editable

In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery
JavaScript
6,477
star
2

react-native-extended-stylesheet

Extended StyleSheets for React Native
JavaScript
2,926
star
3

github-trending-repos

Track GitHub trending repositories in your favorite programming language by native GitHub notifications!
HTML
2,678
star
4

angular-xeditable

Edit in place for AngularJS
HTML
1,913
star
5

awesome-smart-tv

⚡A curated list of awesome resources for building Smart TV apps
1,072
star
6

checklist-model

AngularJS directive for list of checkboxes
HTML
1,051
star
7

bootstrap-editable

This plugin no longer supported! Please use x-editable instead!
JavaScript
558
star
8

await-timeout

A Promise-based API for setTimeout / clearTimeout
JavaScript
428
star
9

playwright-bdd

BDD testing with Playwright runner
TypeScript
302
star
10

combodate

Dropdown date and time picker
JavaScript
208
star
11

autotester

Chrome extension that allows to develop and run automation tests right in browser
JavaScript
170
star
12

clockface

Clockface timepicker for Twitter Bootstrap
CSS
168
star
13

awesome-browser-extensions-and-apps

⚡A curated list of awesome resources for building browser extensions and apps
126
star
14

babel-plugin-runtyper

⚡️ Runtime type-checker for JavaScript
JavaScript
116
star
15

x-editable-yii

Yii extension for creating editable elements
JavaScript
112
star
16

docker-tizen-webos-sdk

Docker image with Samsung Tizen CLI and LG webOS CLI
Dockerfile
94
star
17

tinkoff-invest-api

Node.js SDK для работы с Tinkoff Invest API
HTML
44
star
18

bro-fs

Promise-based HTML5 Filesystem API similar to Node.js fs module
JavaScript
43
star
19

yii-bootstrap-editable

Yii extension for Bootstrap-editable plugin
JavaScript
31
star
20

alice-renderer

Node.js библиотека для формирования ответов в навыках Яндекс Алисы.
JavaScript
30
star
21

playwright-bdd-example

Example project that uses playwright-bdd to run BDD tests
TypeScript
30
star
22

playwright-magic-steps

Auto-transform JavaScript comments into Playwright steps
TypeScript
29
star
23

alice-workshop

Воркшоп по разработке навыка для Алисы на Node.js
JavaScript
28
star
24

js-testrunners-bench

JavaScript test-runners benchmark
JavaScript
27
star
25

groupgridview

Yii extension to group data in your grid
PHP
24
star
26

lazy-model

AngularJS directive that works like `ng-model` but accept changes only when form is submitted (otherwise changes are cancelled)
JavaScript
21
star
27

tinkoff-robot

Пример торгового робота для Tinkoff Invest API (Node.js)
TypeScript
21
star
28

chnl

JavaScript event channels compatible with Chrome extensions API
JavaScript
19
star
29

docker-stack-wait-deploy

A script waiting for docker stack deploy command to complete.
Shell
18
star
30

playwright-network-cache

Cache and mock network requests in Playwright
TypeScript
17
star
31

alice-tester

Библиотека для автоматического тестирования навыков Алисы на Node.js.
JavaScript
14
star
32

promise-controller

Advanced control of JavaScript promises
JavaScript
13
star
33

controlled-promise

Advanced control of JavaScript promises
JavaScript
13
star
34

mocha-es6-modules

Running Mocha tests in the browser with ES6 Modules support
JavaScript
12
star
35

yandex-cloud-deploy-fn

CLI для деплоя функций в Yandex Cloud на Node.js
TypeScript
11
star
36

tinkoff-local-broker

Локальный сервер для тестирования торговых роботов на Tinkoff Invest API
TypeScript
9
star
37

alice-cloud-proxy

Готовая облачная функция для развертывания своего прокси-навыка для Алисы
JavaScript
9
star
38

throw-utils

Helpers for error throwing
TypeScript
5
star
39

wait-for-cmd

A pure shell script waiting for provided command to exit with zero code
Shell
5
star
40

selgridview

Yii extension to keep selected rows in CGridView when sorting and pagination
JavaScript
5
star
41

alice-protocol

JSON схемы запросов и ответов в навыках Алисы
JavaScript
5
star
42

alice-skill-starter

Быстрый старт навыка для Алисы на Node.js
JavaScript
5
star
43

ydb-sdk-lite

Lightweight implementation of Yandex Database SDK for Node.js
JavaScript
4
star
44

flat-options

One-level options with default values and validation
JavaScript
4
star
45

yandex-cloud-fn

Хелперы для функций в Yandex Cloud (Node.js)
TypeScript
4
star
46

alice-testing-example

Пример функционального тестирования навыка для Яндекс Алисы на Node.js.
JavaScript
4
star
47

page-object

A Page Object pattern implementation library for JavaScript
JavaScript
4
star
48

yc-serverless-live-debug-original

Live debug of Yandex cloud functions with local code on Node.js
TypeScript
4
star
49

eslint-plugin-visual-complexity

Enforce a visual complexity of the code
JavaScript
4
star
50

npxd

Run NPX commands inside Docker container
Shell
3
star
51

fetchers

Semantic RESTful Fetch API wrappers
JavaScript
3
star
52

early-errors

A tiny script to catch webpage errors earlier.
JavaScript
3
star
53

json-micro-schema

Minimal JSON schema validation format
JavaScript
3
star
54

loggee

Zero-dependency JavaScript logger with namespaces
JavaScript
3
star
55

selenium-fileserver

Public website serving Selenium self-test static pages
JavaScript
2
star
56

alice-types

Тайпинги для протокола Алисы.
TypeScript
2
star
57

marusya-types

Тайпинги для протокола Маруси.
TypeScript
2
star
58

micro-schema

JavaScript implementation of json-micro-schema validation format
JavaScript
2
star
59

sheeva

Concurrent Automation Test Runner
JavaScript
2
star
60

subpath-imports-typescript

Example of TypeScript project with Subpath Imports
TypeScript
2
star
61

uni-skill

Универсальный интерфейс для разработки навыков голосовых ассистентов.
TypeScript
2
star
62

alice-asset-manager

Node.js API для загрузки изображений и звуков в навык Алисы.
JavaScript
2
star
63

pendings

[DEPRECATED] Better control of promises
JavaScript
2
star
64

playwright-webhook-reporter

Universal Playwright reporter to send test results to any webhook
JavaScript
1
star
65

react-server-actions-jsx

Example Next.js app with server actions returning JSX
TypeScript
1
star
66

skill-afisha-moscow

TypeScript
1
star
67

qrlink

HTML
1
star
68

promised-map

A map of promises that can be resolved or rejected by key
TypeScript
1
star
69

json-paths

Collect different paths of JSON data.
TypeScript
1
star
70

yandex-cloud-fn-internals

Roff
1
star
71

retry

Retry async function with exponential delay, timeouts and abort signals
TypeScript
1
star
72

alice-dev

Инструменты разработчика для навыков Алисы
JavaScript
1
star
73

skill-dev-proxy

Навык для Алисы, позволяющий отлаживать другие навыки прямо на устройстве
TypeScript
1
star
74

logger

Pure typescript logger with levels and prefix support
TypeScript
1
star
75

yandex-cloud-lite

Минимальный Node.js клиент для доступа к API сервисов Yandex Cloud по GRPC
JavaScript
1
star