Using a hook to pass variables between client and server

Plugin Development
  • 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.

  • 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!


Suggested Topics


  • 0 Votes
    2 Posts
    406 Views
  • 0 Votes
    1 Posts
    168 Views
  • 0 Votes
    3 Posts
    212 Views
  • 0 Votes
    1 Posts
    248 Views
  • 1 Votes
    6 Posts
    530 Views