Using a hook to pass variables between client and server



  • I'm trying to pass server-side data into the client side JavaScript file. Is there a way I can do this (maybe using a hook)?

    Sorry, I am new to NodeBB.


  • Community Rep

    The best way is to use socket.io

    You use socket.io to create an event in your server code like so,

    // Require socket.io
    var socketPlugins = require.main.require('./src/socket.io/plugins')
    
    // Your plugin's app.load hook
    plugin.load = function (data, next) {
    
      // Create a socket namespace
      socketPlugins.yourplugin = {}
    
      // Create the event
      socketPlugins.yourplugin.eventname = function (socket, data, callback) {
        // The client will call this event to request data and optionally send its own data.
        // Use the callback to send the data it wants. First parameter is an error value.
        callback(null, {requestedinfo: 'I got the info'})
      }
    
      next()
    }
    

    In the client .js you call the event like so...

    // The middle parameter is optional data you can send to the server.
    socket.emit('plugins.yourplugin.eventname', {}, function (err, data) {
      console.log(data.requestedinfo)
    })
    


  • @yariplus Thanks!


Log in to reply
 

Looks like your connection to NodeBB was lost, please wait while we try to reconnect.