Listen to a channel from any back end file? #4960
-
Hello. I'm hoping to emit from one back end file, and listen to the channel at a different back end file. No front end at all. Emitting file "emit.js"
Listening file "listen.js"
What is the simple way to set this up? Thank you so much!!!! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Are those two files run in the same Node.js process? In that case, you could use a simple
import { WebSocket } from 'ws'
import { EventEmitter } from 'node:events';
const ws = new WebSocket('wss://ws.coincap.io/prices?assets=ethereum')
export const myEventBus = new EventEmitter();
ws.on('message', (event) => {
let data = JSON.parse(event)
myEventBus.emit('test', data)
})
import { myEventBus } from './emit';
myEventBus.on('test', (data) => {
// ...
}); Reference: https://nodejs.org/api/events.html If you have two distinct Node.js processes, then you can indeed create a Socket.IO connection: import { io } from 'socket.io-client'
export const listen = async function (){
const socket = io('http://localhost:3000');
socket.on('test', (data) => {
// ...
})
} |
Beta Was this translation helpful? Give feedback.
Are those two files run in the same Node.js process? In that case, you could use a simple
EventEmitter
:emit.js
listen.js
Reference: https://nodejs.org/api/events.html
If you have two distinct Node.js processes, then you can indeed create a Socket.IO connection: