node.jsexpresssocket.iopkgcloud

In Node.js how to send message to client side from a handler/callback method


I am a beginner in node.js. I am trying to create a webapp using node.js which will create servers in cloud and manage them. After doing some research I've decided to use node.js, socket.io, express and pkgcloud modules to create the webapp. Now, the problem I am facing is that I am unable to send messages to the front-end/client-side when a server is getting created. The server is getting created successfully but I am not getting how to send the server status to the browser screen.

Here's the code: index.js

var express = require('express'),
app = express();

app.use(express.static(__dirname + '/'));

var io = require('socket.io').listen(app.listen(1337));

io.sockets.on('connection', function(socket) {
    socket.on('mesg_to_server', function(data) {

       // This is for testing whether we're receiving msgs on client side
       io.sockets.emit("mesg_to_client",{ mesg: data["mesg"], mesg1: data["mesg1"] });

       var Rackspace = require('./ex_rackspace');
       var rackspace = new Rackspace();
       rackspace.create(data.mesg);
   });
}); 

ex_rackspace.js:

  var pkgcloud = require('pkgcloud'),
  _ = require('./node_modules/pkgcloud/node_modules/underscore');

  var client = pkgcloud.providers.rackspace.compute.createClient({
                 username: 'xxxx',
                 apiKey: 'xxxxx',
                 region: 'HKG'
              });

  // This function will handle our server creation,
  // as well as waiting for the server to come online after we've
  // created it.
  function handleServerResponse(err, server) {
     if (err) {
       console.dir(err);
       return;
     }

     console.log('SERVER CREATED: ' + server.name + ', waiting for active status');

     // Wait for status: ACTIVE on our server, and then callback
     server.setWait({ status: server.STATUS.running }, 5000, function (err) {
      if (err) {
        console.dir(err);
        return;
      }

      console.log('SERVER INFO');
      console.log(server.name);
      console.log(server.status);
      console.log(server.id);

      console.log('Make sure you DELETE server: ' + server.id +
  ' in order to not accrue billing charges');
  });
  }

  var Rackspace = function() {

  };  

  Rackspace.prototype.test = function (text) {
     console.log("provider: Rackspace: " + text);
  }       

  // first we're going to get our flavors
  Rackspace.prototype.create = function (server) {
     client.getFlavors(function (err, flavors) {
     if (err) {
       console.dir(err);
       return;
     }

     // then get our base images
     client.getImages(function (err, images) {
       if (err) {
         console.dir(err);
         return;
       }

       var flavor = _.findWhere(flavors, { name: '1 GB Performance' });

       var image = _.findWhere(images, { name: 'CentOS 5 (PV)' });

       // Create our first server
       client.createServer({
          name: server,
          image: image,
          flavor: flavor
       }, handleServerResponse);
     });
   });
  }

  module.exports = Rackspace;

page.html (client-side):

<!DOCTYPE html>
<html>
  <head>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
        // our socket.io code goes here
        var socketio = io.connect("127.0.0.1:1337");

        socketio.on("mesg_to_client", function(data) {
            document.getElementById("chatlog").innerHTML = ("<hr/>" +
            data.mesg + ' ' + data.mesg1 + document.getElementById("chatlog").innerHTML);
        });

        socketio.on("test_output", function(data) {
            console.log(data.mesg); 
        });

        function sendMessage() {
            var msg = document.getElementById("mesg_input").value;
            socketio.emit("mesg_to_server", { mesg : msg, mesg1 : "here"});
        }

    </script>
 </head>
 <body>
    <input type="text" id="mesg_input"/>
    <button onclick="sendMessage()">Create</button>
    <div id="chatlog"></div>
 </body>
</html>

Solution

  • You need to add a callback to the create function

    Rackspace.prototype.create = function (server, callback){
         //your code - if err send error else send success message
         callback(err, message)
    }
    

    Then use it when you call create

    rackspace.create(data.mesg, function (err, message){
         //your code with your socket emit here
    });