I'm trying to create a notification feature in Node.JS using Socket.io, and Javascript.
The app.js (the entry script) imports the server.js script (which contains the API endpoints).
Socket.io then listens to app.js (const io = socket(server)) and notifies index.html if any notification messages are emitted by the server.
The code works fine if I combine app.js and server.js into one script.
The problem is, when I separate the scripts into a microservices architecture like below, the messages aren't showing.
I can't figure out how to emit a socket.io message from server.js when I split the endpoint code into another script like below.
I've tried importing socket.io-client into server.js, then using const socket=io(), and emitting a message using socket.emit('notification','Task completed..!'). But this doesn't work.
Could you please help me spot the problem?
Thanks in advance!
app.js:
const app = require('./server');
const socket = require("socket.io");
const port = 6000;
const server = app.listen(port, () => {
console.log(`App started on port ${port} ...!`)
})
const io = socket(server);
module.exports={io};
server.js:
const express = require('express');
const io = require('socket.io-client');
const socket=io();
// Express configurations
const app = express()
app.get('/start', (req, res) => {
// Task completed notification
io.on("connection", (socket)=>{
socket.emit('notification',`Task completed..!`);
});
});
// Export app
module.exports = app;
index.html:
<html lang="en">
<head>
<title>Notify</title>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="/assets/js/jquery.js"></script>
<script>
var socket = io();
socket.on('notification', (msg) => {
// Create notification element
var nb = ` ${msg} `;
$('#messages').html(nb);
});
</script>
<body>
<span id="messages"></span>
</body>
</html>
Fixed it!
app.js:
const app = require('./server');
const socket = require("socket.io");
const port = 6000;
const server = app.listen(port, () => {
console.log(`App started on port ${port} ...!`)
})
const io = socket(server);
exports.io=io; // added
server.js:
const express = require('express');
const io = require('socket.io-client');
const socket=io();
// Express configurations
const app = express()
app.get('/start', (req, res) => {
// Task completed notification
require('./app').io.emit('processing',`Task Completed..!`); // updated
});
// Export app
module.exports = app;
index.html:
<html lang="en">
<head>
<title>Notify</title>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="/assets/js/jquery.js"></script>
<script>
var socket = io();
socket.on('notification', (msg) => {
// Create notification element
var nb = ` ${msg} `;
$('#messages').html(nb);
});
</script>
<body>
<span id="messages"></span>
</body>
</html>