Search code examples
ajaxnode.jscomet

Any way to push Javascript from NodeJS server to client for updates?


In Scala's Liftweb there are some classes which allow for Javascript to be pushed to the browser via comet/ajax after the page has loaded. Some documentation here.

The usage could be for example when someone submits a form to the server, the form would submit via AJAX and then some Javascript can be sent from the server to the client to show some error message. Well this is just for example, there are better ways to do form validation.

Is there any way to push Javascript from the NodeJS server to the client to do updates? Any standard way to do this? Why I want to do this is that its nicer to have all client and server code located in one server file.

Also as a secondary question, can I access the page data from the server side? It would be nice to be able to query a page element from the server side or query some page data from the server side.


Solution

  • You can build this functionality into socket.io, either by predefining functions based on dynamic objects that are sent bi-directionally, or by building a system which will parse and run javascript from both sides. Depending on what you are trying to do it might take a while to get that working for you securely (not just throwing everything in eval());

    http://socket.io/

    Alternatively there is a library built on node.js that has this functionality built in. I have not personally used it so I can't attest to the reliability or security of the system, but it should be a good place to start.

    http://www.nowjs.com/
    https://github.com/Flotype/now

    Hope this helps!