how to make sockets in plugin working
-
wrote on 28 Feb 2025, 11:24 last edited by
Good day. I'm learning how to use sockets work in plugins
'use strict'; const pluginSockets = require.main.require('./src/socket.io/plugins'); module.exports = function(params) { // Add custom function to the sockets object pluginSockets.customFunc = function(socket, data, done) { const response = 'Hello from server'; done(null, response); }; };
then I open Developer Tools in Firefox and enter
var script = document.createElement('script'); script.src = '/socket.io/socket.io.js'; document.head.appendChild(script); script.onload = function() { console.log('Socket.IO library loaded successfully'); // Connect to the socket var socket = io.connect(); // Emit the custom event and handle the response var dataToFetch = {}; // Replace with actual data if needed socket.emit('plugins.customFunc', dataToFetch, function(err, data) { if (err) { console.error('My socket customFunc', err, data); } else { console.log('Do stuff with this:', data); // Display the response alert(data); // Optionally show an alert } }); }; script.onerror = function() { console.error('Failed to load Socket.IO library'); };
This doesn't work. Could someone tell me how to fix it?
Thank you. I'm new to Node.js and Nodebb. -
wrote on 28 Feb 2025, 12:54 last edited by
You can just use the below on the server side and it should work.
'use strict'; const pluginSockets = require.main.require('./src/socket.io/plugins'); pluginSockets.customFunc = async function(socket, data) { const response = 'Hello from server'; return response; };
-
wrote on 28 Feb 2025, 13:26 last edited by
Could someone explain me the difference between
1)const pluginSockets = require.main.require('./src/socket.io/plugins');
and
2)var websockets = module.parent.require('./socket.io');
-
wrote on 28 Feb 2025, 14:56 last edited by
First one is the suggested way of requiring core files,
require.main
always references the root of the nodebb folder so you don't have to worry about the require path when moving it around. Meanwhile module.parent references the parent module that required the module so you might have to update the path if you move it into a subfolder for example.