npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ws-await

v4.2.3

Published

Modification of the module ws to wait for a response

Downloads

49

Readme

ws-await: modification of the module ws to wait for a response

Version npm Linux Build Coverage Status

ws-await adds new methods and options to the ws module to allow you to wait for a specific message.

Note: This module does not work in the browser. All the basic ws documentation is here. This module only adds new methods and properties and does not affect the old ones(except Send method - it became asynchronous).

This module has Typescript definitions!

Table of Contents

Installing

npm install ws-await

API docs

See /doc/ws.md to view detailed information.

WebSocketAwait options

New methods and options have been added to this module. Be careful when using them: read the API documentation carefully.

The module includes several settings and options for convenient operation. All options are passed as options(for both client and server):

const WebSocketAwait = require('ws-await');

const options = {
    awaitTimeout: 10000,
    leaveAwaitId: false,
    packMessage: data => JSON.stringify(data),
    unpackMessage: data => JSON.parse(data),
    generateAwaitId: () => `_${Math.random()
        .toString(36)
        .substr(2, 10)}`,
    attachAwaitId: (data, id) => Object.assign({awaitId: id}, data),
    extractAwaitId: data => data &&
        Object.prototype.hasOwnProperty.call(data, 'awaitId') && data.awaitId,
    deleteAwaitId: data => delete data.awaitId,
};
const wss = new WebSocketAwait.Server({port: 5050, ...options});
const ws = new WebSocketAwait(`ws://localhost:5050`, options);

All settings and options presented above are set by default. Please consider this. For example, the package Message method is triggered immediately before the message is sent by all available methods (send, sendAwait, resAwait). That is, by default, function JSON.stringify(data) will work before sending and JSON will be sent. The situation is similar with the unpack Message. The function JSON.parse(data) will fire immediately before the message event is triggered. To disable these two methods (pack Message and unpack Message), use the setSettings method and set the values of these methods to null. Disabling works only on these two methods!

const options = {
    packMessage: null,
    unpackMessage: null,
}

If you do not want to use the sendAwait and resAwait methods, set extractAwaitId to null(due to the fact that there will be no checks for the presence of the awaitId(default) key , performance will be improved).

const options = {
    extractAwaitId: null,
}

All methods and properties are described in detail in the docs.

Usage examples

Examples are for informational purposes only!

Simple send and receive

Send and receive a message waiting for a response.

const WebSocketAwait = require('ws-await');

const wss = new WebSocketAwait.Server({
    port: 8080
});

wss.on('connection', ws => {
    ws.on('messageAwait', (msg, id) => {
        console.log(`Server get messageAwait <<< ${msg.foo} and ${id}`);
        ws.resAwait({
            bar: 'foo'
        }, id);
    });
});

const ws = new WebSocketAwait('ws://localhost:8080');

ws.on('open', async () => {
    const waiting = await ws.sendAwait({
        foo: 'bar'
    });
    console.log(`Client get waiting <<< ${waiting.bar}`);
});

Sending to two servers

Sending to two servers and waiting for messages from them using Promise.all().

const WebSocketAwait = require('ws-await');

const wssOne = new WebSocketAwait.Server({
    port: 5050
});

const wssTwo = new WebSocketAwait.Server({
    port: 8080
});

wssOne.on('connection', ws => {
    ws.on('messageAwait', (msg, id) => {
        console.log(`Server One get messageAwait <<< ${msg.foo} and ${id}`);
        ws.resAwait({
            bar: 'fooOne'
        }, id);
    });
});

wssTwo.on('connection', ws => {
    ws.on('messageAwait', (msg, id) => {
        console.log(`Server Two get messageAwait <<< ${msg.foo} and ${id}`);
        ws.resAwait({
            bar: 'fooTwo'
        }, id);
    });
});

const wsOne = new WebSocketAwait('ws://localhost:5050');
const wsTwo = new WebSocketAwait('ws://localhost:8080');

setTimeout(async () => {
    const wsOneData ={
        foo: 'barOne',
    };
    const wsTwoData ={
        foo: 'barTwo',
    };
    const [waitingOne, waitingTwo] = await Promise.all([wsOne.sendAwait(wsOneData), wsTwo.sendAwait(wsTwoData)]);
    console.log(`Client One get waiting <<< ${waitingOne.bar}`);
    console.log(`Client Two get waiting <<< ${waitingTwo.bar}`);
}, 1000);

With change attachAwaitId settings and catch Error

Send and receive a message waiting for a response with change attachAwaitId settings and catch Error.

const WebSocketAwait = require('ws-await');

const wss = new WebSocketAwait.Server({
    port: 8080,
});

wss.on('connection', ws => {
    ws.on('messageAwait', (msg, id) => {
        console.log(`Server get messageAwait <<< ${msg.foo} and ${id}`);
        ws.resAwait({
            bar: 'foo',
        }, id);
    });
});

const ws = new WebSocketAwait('ws://localhost:8080', {
    attachAwaitId: (data, id) => {
        if (typeof data === 'object') {
            return Object.assign({awaitId: id}, data);
        }
        throw new Error('Data is not object');
    },
});

ws.on('open', async () => {
    try {
        const waitingOne = await ws.sendAwait({
            foo: 'bar',
        });
        console.log(`Client get waiting <<< ${waitingOne.bar}`);
        const waitingTwo = await ws.sendAwait(10);
        console.log(`Client get waiting <<< ${waitingTwo.bar}`);
    } catch (err) {
        console.log(err.message);
    }
});

Сhain from sending and receiving a message

Send and receive a message waiting for a response. The server also sends a waiting message to another server and sends it to the first server when it receives a response.

const WebSocketAwait = require('ws-await');

const wssOne = new WebSocketAwait.Server({
    port: 5050
});

const wssTwo = new WebSocketAwait.Server({
    port: 8080
});

const wsTwo = new WebSocketAwait('ws://localhost:8080');

wssOne.on('connection', ws => {
    wsOne.on('open', async () => {
        ws.on('messageAwait', async (msg, id) => {
            console.log(`Server One get messageAwait <<< ${msg.foo} and ${id}`);
            const resData = await wsTwo.sendAwait({
                foo: 'bar'
            });
            ws.resAwait(resData, id);
        });
    });
});

wssTwo.on('connection', ws => {
    ws.on('messageAwait', (msg, id) => {
        console.log(`Server Two get messageAwait <<< ${msg.foo} and ${id}`);
        ws.resAwait({
            bar: 'I am from wssTwo server'
        }, id);
    });
});

const wsOne = new WebSocketAwait('ws://localhost:5050');

wsOne.on('open', async () => {
    const waiting = await wsOne.sendAwait({
        foo: 'bar'
    });
    console.log(`Client get waiting <<< ${waiting.bar}`);
});

Suggestions and questions

Send your suggestions and questions on GitHub or send to email. [email protected].

Changelog

We're using the GitHub releases for changelog entries.

License

MIT