Creating a Node.js WebSocket client

The ws module also allows us to create a WebSocket client outside of the browser environment.

Let's see if we recreate equivalent (and enhanced) functionality to our browser app in the terminal. Essentially, we're going to create a generic interactive WebSocket testing command-line tool!

We'll start by creating a new folder called websocket-client with an index.js file. We'll also need to create a package.json and install the ws module:

$ mkdir websocket-client $ cd websocket-client $ npm init -y $ npm install --save ws 

Now let's open index.js in our favorite editor, and begin by requiring and initializing the ws module and the core readline module:

const WebSocket = require('ws') const readline = require('readline') ...

Get Node Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.