Missing support for Node.js
Opened this issue · 6 comments
I tried using "robust-websocket" with a Node.js application but it doesn't work. The error message is:
D:\dev\projects\temp\socket-chat-example\node_modules\robust-websocket\robust-websocket.js:7
module.exports = factory(global, navigator)
^
ReferenceError: navigator is not defined
at realWs.close (D:\dev\projects\temp\socket-chat-example\node_modules\robust-websocket\robust-websocket.js:7:38)
at Object. (D:\dev\projects\temp\socket-chat-example\node_modules\robust-websocket\robust-websocket.js:12:3)
The navigator object is only available in browsers and I read that "robust-websocket" has been built for browsers but couldn't you use the same code in Node.js when ws is available?
I am thinking of something like this:
let WebSocket;
if (typeof exports === 'object') {
// Node.js, CommonJS
WebSocket = require('ws');
} else {
WebSocket = window.WebSocket;
}
// "robust-websocket" magic here...
It looks like navigator.onLine
is only being used to stop reconnect attempts when the browser is offline. One option to get around this would be offering a feature flag, so that a "robust-websocket" can be initialized without running these navigator.onLine
check (in case people don't want to use it or are running a Node.js app like me).
This is a browser only library that wraps the browser-only W3C WebSocket
protocol . Node.js is entirely different with various clients at your disposal - I recommend ws
@bennyn The navigator
is easy to fix. Just add the following code before you import robust-websocket
.
let navigatorMock = {onLine: true};
global.navigator = navigatorMock;
The harder problem is to fix the CustomEvent
which is also not part of Node.js. The polyfill on MDN uses window.Event
of which I can't find any polyfill.
I need to port this to Node.js because I am using Jest to unit-test the stuff. And Jest is using Node.js rather than browser API.
@hktonylee Instead of using the CustomEvent interface you can have a look at Node.js' EventEmitter.
And if you need a reconnecting WebSocket implementation (which works in Browsers & Node.js), I recommend you reconnecting-websocket. It has multiplatform support and we are using it at Wire for our wire-web-api-client.
@bennyn Yes I read the EventEmitter
before but it is not fully complied to Event
. So I decided to switch to other WS wrapper. And thanks for your recommendation which looks very good. I will test it soon in some internal project.
hmm interesting that project has no dependencies. Perhaps this project support node via EventEmitter
instead of CustomEvent
. I do like using CustomEvent
in the browser to be more standard compliant in that execution environment.