'Export the same websocket connection to different files
To clarify, I've set up a websocket that sends back some data every few mins, and based on the data that is being sent back, I would like to run some routine on that data. And I'd like to continue running different routines using the same websocket at different times of the day. I need the streaming data, but I also need to have an event listener. My thought would be start up the websocket in a different file then export it to different files in the folder, but this doesn't work since a new websocket starts up. I can only have 1 websocket connection at a time.
For example:
openConnection.js
(() =>
{
const url = "wss://stream.data";
const ws = new WebSocket(url);
ws.on('open', () =>
{
ws.send(`{"authorize"}`);
});
module.exports = ws;
})();
then ->
someFunction.js
const ws = require('./openConnection.js');
function foo ()
{
// using the imported websocket
ws.addEventListener('message', (data) =>
{
doSomething(data)
});
}
Is there a way for me to use the same websocket connection throughout different files?
Solution 1:[1]
I don't know if this will help you but when using socket.io and express you can simply pass io server to locals
here is the example
const server = http.createServer(app);
// Create HTTP server
const io = new Server(server, {
cors: {
origin: '*',
},
}); // Create Socket.io server
app.locals.io = io; // Set io to global
in other files
const { io } = req.app.locals;
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
Solution 2:[2]
Using CommonJS modules with module.exports and require():
const url = "wss://stream.data";
const ws = new WebSocket(url);
ws.on('open', () =>
{
ws.send(`{"authorize"}`);
});
module.exports.ws = ws;
and, to import that in a CommonJS module:
const { ws } = require('./openConnection.js');
function foo ()
{
// using the imported websocket
ws.addEventListener('message', (data) =>
{
doSomething(data)
});
}
And, you can use that same const { ws } = require('./openConnection.js'); from any other file because module handles are cached so the 2nd, 3rd, 4th times you require() it in, they just return the previous module.exports object.
Life will be simpler if you don't try to mix CommonJS modules and ESM modules. So, module.exports is used with require() in a CommonJS module and import is used with export in an ESM module.
There are ways to load one type of module from the other, but life gets a lot more complicated as soon as you try to do that so it is best to stick with one module type if possible.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucjan Grzesik |
| Solution 2 | jfriend00 |
