Sitemap
Better Practices

For individual engineers to the largest teams, Better Practices is intended to distill knowledge from the Postman community. This is a place to learn about modern software practices together! Read more: https://medium.com/better-practices/introducing-better-practices-e9cf14cf0c88

Follow publication

Set Up a WebSockets Server in Node.js

Joyce Lin
5 min readFeb 1, 2023

--

According to the Postman State of the API report, WebSockets are used by 26% of respondents.

Pre-requisites

Create the Node.js server

mkdir websockets
cd websockets
npm install ws
One sub-directory and two files at the first level of the root directory.
{
"type": "module",
"dependencies": {
"ws": "^8.12.0"
}
}
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
console.log('received: %s', data);
});

ws.send('something');
});
node index.js

Send and receive WebSocket messages

Connect to local server and receive a WebSocket message.
Inspect handshake details.
Filter or search for specific messages in the Messages pane.

Send system information

npm install systeminformation
import si from "systeminformation";
 setInterval(async () => {
const cpuTemp = JSON.stringify(await si.currentLoad());
ws.send(cpuTemp);
}, 1000);
node index.js
Local server sends CPU data every one second.
Expand message details.

Additional resources

--

--

Better Practices
Better Practices

Published in Better Practices

For individual engineers to the largest teams, Better Practices is intended to distill knowledge from the Postman community. This is a place to learn about modern software practices together! Read more: https://medium.com/better-practices/introducing-better-practices-e9cf14cf0c88

Joyce Lin
Joyce Lin

Written by Joyce Lin

coding and cats in San Francisco

Responses (1)