Node.js method invocation remotely

I am taking my first steps with Node.js
and I was wondering whether there is some way to invoke a JS method define server-side (using Node.js
) but from the client side. e.g.

function read_file_server_side(id){
  // Do stuff on the server side.
}

and then, from the client side we need to be able to invoke the method. Of course, I understand that it is possible to wrap the server-side method using REST principles; i.e. expose it to the client as a web service and have the clients using HTTP requests. But it comes handy if one could make use of the function directly.

Problem courtesy of: Pantelis Sopasakis

Solution

Instead of socket.io, I’d rather point you to Now.js
. It does exactly what you want : share functions server side on the client side.

Solution courtesy of: Florian Margaine

Discussion

Well the thing about node is there is modules for everything.‌ For everything there is an “initial commit” and most probably in github. For this case, it’s part of every app to make a request to server from client side or in other words to make a RPC call. The basic transport method in this case is ajax. And on some modern browsers, we have websockets. For ajax, this is the simplest method that you can make something you want:

On client side:

var request.ajax('/ajax/setLolz', {data : 'nice', type : 'post'})

request.done(function(msg) {
  $("#lolz").html( msg );
});

on server side:

var url  = reruire('url')
var http = require('http');
var lolz = 'wow';
var methods = {
  '/ajax/setLolz' : function (action, body, res) {
    res.end(lolz);
    lolz = body;
    someOtherFunction();
  }
}

http.createServer(function (req, res) {
  var body = '';
  var action = url.parse(req.url);

  req.on('body', function(text) {
    body += text;
  }

  req.on('end', function() {
    methods[action.path](action, body, res);
  }

}).listen(1337, '127.0.0.1');

This was simple ajax. You make it a little better by using connect
:

var connect = require('connect');
var app = connect()
  .use(connect.bodyParser())
  .use(function(req, res){
    var action = url.parse(req.url);
    methods[action.path](action, body, res);
  })
 .listen(1337);

Or more simpler with express
:

var app = require('express');
var app = express.createServer()
  .use(express.bodyParser());

app.get('/ajax/setLolz', function(req, res){
  res.end(lolz);
  lolz = req.body;
  someOtherFunction();
});

app.listen(1337);

And yeah, there lots of modules
that can help you.

As of websockets, the most fastest websocket server that I know is ws
. Though some browsers may not support it.

On client side:

websocket = new WebSocket('ws://www.host.com/ws');
websocket.onopen = function(evt) {
  websocket.send(JSON.stringify({method : 'setLolz', msg : 'yes '};
};
websocket.onmessag = function(evt) {
  $("#lolz").html( evt.data );
}

On server:

var WebSocket = require('ws');
var ws = new WebSocket('ws://www.host.com/ws');
var methods = {
  'setLolz' : function (msg, ws) {
    ws.send(lolz);
    lolz = msg;
    someOtherFunction();
  }
}

ws.on('message', function(data, flags) {
  data = JSON.parse(data);
  methods[data.method](data.msg);
});

Then there’s the socket.io
, that makes things much easier. It’s cross browser and works everywhere. Built on ajax and websockets and some other methods. You patch everything to events. You can even use it beside an http server listening on the same port.

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

io.sockets.on('connection', function (socket) {
  socket.on('setLolz', function(data) {
    socket.emit('lolz', lolz);
    lolz = data;
  });
  socket.on('setLolz', someOtherFunction);// Yes, you can listen to an event with two functions
});

But still it’s not simple enough, so now I introduce you to nowjs
.

On browser:

now.setLolz(function(data){
  $("#lolz").html( data );
});

On server side:

var nowjs = require("now");
var app = nowjs.initialize(httpServer);

app.now.setLolz = function(cb){
  cb(lolz);
  lolz = data;
  someOtherFunction();
}

I don’t wanna go in deeper, but I hope you got the gist. There are also other modules(dnode, hook.io, flatiron, railwayjs, racer, locomotivejs, …) that can help you. And yes, you can always make your own.

Happy coding… :D

Discussion courtesy of: Farid Nouri Neshat

Have a look here: Socket.IO

You basically can call a method on the server side easy and fast.

Server:

socket.on('doAwesomeStuff', function (data) {
   startDoingAwesomeStuff();
}

function startDoingAwesomeStuff() {
   // this would be the remotely invoked method.
   ...
}

Client:

socket.emit('doAwesomeStuff', { my: 'data' });

Discussion courtesy of: Codrin Eugeniu

This recipe can be found in it’s original form on Stack Over Flow
.

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Node.js method invocation remotely

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录