Why websocket cannot connect in the custom node

I have developed a custom node, and I want to connect a websocket server in it. But it cannot work and doesn’t have any error display.
The code is below:

import * as  WebSocket  from 'ws';

async execute(this:  IExecuteFunctions): Promise<INodeExecutionData[][]> {
	const ws = new WebSocket(`ws://`);
	ws.onopen = function() {
	   console.log('connect success')

The first console can work normally, the the second console doesn’t show and has no error.
Is the n8n blocks websocket connect?

Hey @vanessa,

I have not used the web socket library before so I set up a quick web socket test server using

import { WebSocketServer } from 'ws';

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

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

Then for my node I have used what you put above but it looks like the connection is not being opened and the node is finishing before it has had a chance to properly connect.

If I use the below in my node code:

const ws = new WebSocket('ws://');
await new Promise(resolve => ws.once('open', resolve));
ws.send('n8n rocks!');

It waits for that connection to be opened then sends the message so my server output is:

[email protected]:~/Code/javascript/Websocket$ node socket.js
connection made
received: n8n rocks!

Hopefully this helps :+1:


Thank jon, It work. :partying_face:


@vanessa - would you be able to share your custom node? I’m looking for a WebSocket listener capability myself and would rather not reinvent the weel…