Running Page Specific Javascript in node.js - javascript

I am working on a project which allows users to monitor energy consumption. The main dashboard page is a web app which is pretty neat and makes extensive use of javascript and ajax. The server currently runs apache and uses php; however, I am planning on installing node.js and updating the server side scripts in order to support websockets (and I also like the idea of using javascript on the server and client side).
I have followed several online introductions but I am struggling to find answers to specific questions which I need to get my head round before I can start, one of which is outlined below.
Is there a simple way to run page-specific javascript on the pages of the website in the same way you would with PHP? I have come across templating (for example using mustache), but I don't understand whether it is possible to run specific modules of javascript on the server when a specific file is about to be served.
Thank you very much for taking the time to read my questions. If you can answer any of them, or even provide any general advice, it would be greatly appreciated.

You should be looking into web frameworks for Node.js that help you with this kind of thing. My favorite is express.
Express will allow you to map a "route" to a handler, and that handler can be in any file you want. E.g.,
app.get('/energy/page-x', require('./routes/page-x-handler'));
Where ./routes/page-x-handler.js is something like:
module.exports = function (req, res, next) {
res.render('template-name');
}

If you use a framework like Express you can 'intercept' (or 'route', as it's called) requests for specific URL's and run server side JS to handle that URL (including, at the end of processing, render and return a template).
One of the differences with PHP is that PHP often mixes templates and code into one file, whereas with Node, those two are usually separated (so you have a clear separation between code and layout).

Related

Creating a single page web app as part of a website

I am working on a project which allows users to monitor energy consumption. The main dashboard page is a web app which is pretty neat and makes extensive use of javascript and ajax. The server currently runs apache and uses php; however, I am planning on installing node.js and updating the server side scripts in order to support websockets (and I also like the idea of using javascript on the server and client side).
I have followed several online introductions but I am struggling to find answers to specific questions, one of which is outlined below.
All guides to node seem to only support single page web apps. This is an issue as there are a number of different pages which require files to be served. How can I support file serving but enable one of the pages to use websockets. Does this functionality, which is only required for one page, need to be coded into the main server script on the site or is there a way of separating this so that the server goes to server the dashboard html file and then discovers that the file requires specific websocket dependencies?
Thank you very much for taking the time to read my questions. If you can answer any of them, or even provide any general advice, it would be greatly appreciated.
1: The only reason the guides do single page web apps is because that's node's forte. Node.js serves static files and rendered templates just fine. Just include the JS for the websockets only in the pages that need it.
2: It's not quite as simple as with php, but take a look at express.js
3: Yes, and really you shouldn't even need different ports, you can write a proxy in node in one line.
4: CentOS is fine, node is platform agnostic. All the linuxes have top support followed by osx, solaris and windows.

GWT server with get() and post() built on client end

This is more of a curiosity really, to see if some one has done anything similar, or if at all it is possible.
I'm working on a project that will get notification through external notifications. Now I could go about doing this by having notifications coming to my server and have a comet setup between my client and server.
BUT
I was wondering if I could write server logic into my client and listen out for notifications from external sources. Immediately one issue I see is, external sources would need callback URL etc, which I dont know if you could do from client side (unless one could use the IP address in that way).
As you can see it is more ideas and discussions if such a thing was possible, this is somewhat inspired by P2P models whereby you wouldn't be mediating things through your central server.
Thanks in advance!
GWT compiles (nearly) Java source into JavaScript, so compiled GWT apps can't do anything that traditional JavaScript running in the browser cannot do. The major advantage of bringing Java into the picture isn't automatic access to any/all JVM classes, but the ability to not only maintain Java sources, which tend to be easier to refactor and test as well as keep consistent with the server, and to compile that statically defined code into JavaScript, performing all kinds of optimizations at compile time that aren't possible for normal JavaScript.
So no, while you can have some code shared by the client (in a browser) and the server (running in a JVM), you can't run Tomcat/Jetty/etc in the browser just by using GWT to compile the java code into JS.
As you point out, even if this was possible, it would be difficult to get different clients to talk back and forth, without also requiring that the browsers can see and connect at will to one another. BitTorrent and Skype have different ways for facilitating this, and currently browsers do not allow anything like this - they are designed to make connections to other servers, not to allow connections to be made to them.
Push notifications from the web server to the browser are probably the best way forward, either through wrapping comet or the like, or through an existing GWT library like Atmosphere (see https://github.com/Atmosphere/atmosphere/tree/master/samples/gwt-demo for a demo).

Passing query variables to JavaScript to load - is JavaScript on the backend of these APIs?

I've been looking at the API for Flattr, http://flattr.com/support/integrate/js , which has a cool way of accepting query variables for their JavaScript to load.
My question is, do most APIs use something other than JavaScript to accept these different variables for their services? EG:
Ruby on Rails
PHP
Python
Then these are parsed by the respective language and returned as outputted JavaScript to the requesting website?
Cheers
Javascript itself is totally capable of reading how it's embedded to the HTML it belongs to, by reading document.getElementsByTagName("script") and further parse/match their src attributes. Therefore, it's not a problem at all for it to further parse the query variables attached at the end, and dynamically (all in javascript, client side) load components within.
Any javascript libraries that allow you to pack the whole thing and deploy to your own web server should take this approach, since there's no server to handle the request anyways.
On the other hand, javascript libraries that are hosted on other sites that allow you to use (like YUI) MAY take the server approach like you mentioned.
In my personal experience, projects that I have worked on have used server side languages to deal with get params.
So a request might be /myjavascript.js?id=123123 The server side language would create the correct javascript for that request.
Keeping everything on the server side has the advantage of not allowing the user to see what is going on. If this isn't a problem for you, javascript is more than capable of handling different params.
In my experience it's fairly common that widgets embedded into others' sites gets their parameters by parsing them from their script tags. It makes the widget script static and self-contained and thus easier to distribute through eg. a fast CDN. Performance is important when you're going to convince someone else to add your javascript to their site as poor performance from the widget can make the entire site appear sluggish.
A better place to specify the parameters than query parameters would however be to specify them in the URL:s hash-part as that part isn't included when caches are checked and thus the script would have to be downloaded fewer times - which of course is good for performance, especially if the parameters might shift a lot.

How should I go about writing a node.js web application with both server and client side code?

I'm planning on writing a spine/backbone.js style web application which basically just transfers a large application.js file to the client's browser that communicates with the node.js backend using ajax. The problem is that I don't know how to structure such a project, since I've never seen examples of such an application. I can picture some pros and cons with different ways of doing this
Keep everything in one project folder. Both the server side and client side code resides in the same folders which means they can share resources such as form input validation and language files. This seems like a good solution, but I have no clue how I would bundle only the code that the client needs, and not the server code. Just in general I don't know how to accomplish this. If it has been done before, I would like to see some sample code, perhaps even a git repo
Create two separate projects. One for the client and one for the server. This seems a lot more simple and straight forward, but not as elegant when it comes to sharing resources. I would have to write code such as form input validation twice.
Any thoughts?
Your first situation is a very tricky scenario and I would suggest that we're not quite there yet. Some would argue that there's little reason to try to get there, as front/back ends will always be tasked with slightly and sometimes drastically different tasks. Libraries like derby show promise, but aren't quite there yet.
I discussed this recently with a friend and we came to the conclusion that perhaps the best bet for now would be to serialize models over websockets, and then ensure that the node server and client app stay in sync.
I may work on such a library, but for now I'm still developing with 2 folders and copies of models on both sides. Layout mark-up gets sent from the server, with all other content rendered client-side after receiving JSON from the server. Frankly, the amount of duplication isn't really that substantial. A little irritating but also maintains greater flexibility to grow in different directions.
This won't be a complete answer to your question, but one library that might help if you choose to pursue such an endeavour might be Browserify.
It's designed so you can use a similar require() function with a preprocessed, or on-the-fly generated from module source, js file containing many different modules. These modules can be shared with the server side through the same require() mechanism.
I don't know explicity of a Backbone implemented on the server side as a server side counter part for model sync, that would seem to be the first goal you are looking for, aloowing code that makes sense to be shared, such as models and validation, to be usefully shared.
Another thing to look at is requirejs, which uses more traditional script tag asynchronous loading f js modules, but also works within node.js aloowing the same AMD modules to a be shared between node and client code.
Was realtime required? Otherwise the Derby approach might be a little too heavy. Express.js proposes a structure where client js is separated in public folder, and provides methods to get a quick RESTful API running, which you can then access with your application.js.
I guess you could load "classic" js files from public into node via eval() too.
Things have moved much ahead now, and things like
browserify influenced coding can help us achieve this easily
there will always be some uncommon code between server and client sides, But the goal shall always be to keep all the logic code in different modules(which are later used from both environments). This is better from TDD point of view as well, also keeps your keyboard press count to lesser.
Have a look at things like this stack -
http://mindthecode.com/lets-build-an-angularjs-app-with-browserify-and-gulp/
Having said that your option1 did not seem that manageable to me, if you had the right coders coding the right code.

Can I use a Node.js 'mirror' as fallback when JavaScript not supported?

The basic question
Is it possible to fallback to a server-side Node.js implementation of an existing client-side, JavaScript-heavy site. Specifically for users who don't have JavaScript (or perhaps, if the client's browser fails to meet certain performance requirements)?
I'm really after an architecture thats a literal interpretation of slide 8 of this presentation.
Rather than mustache/backbone forming data structures and creating views on the clientside, instead this would be done in Node and the the fully-formed HTML could be returned.
Background
I have written an application that is built on a stack of jQuery, Underscore, Backbone and Mustache (making RESTful API calls to a web service for data).
This all works very well with JavaScript enabled in the browser, but I haven't yet written a server-side implementation as a fallback.
Of course I could essentially 're-write everything' in C#.NET/Python/Ruby/etc., but this seems like a very poor solution, when you consider the amount of duplication and added maintenance, when there is a fully functional version of the application available in JavaScript.
You can do this. It is even easier using something like express.js: http://expressjs.com/
Express.js, for example, has a function called res.render() which will render a template for you (in a wide array of templating languages).
The functionality of your client side app will have to be rewritten to work without js (clearly). But you could even dynamically generate anchor tags and pass them in as variables to your templates on the server.
Example responding to whatever.com/test that renders the template index.jade with the title variable set to 'My Site':
app.get('/test', function(req, res){
res.render('index.jade', { title: 'My Site' });
});
As for reusing your entire backbone app on the server, I would imagine it is possible using jsdom and rewriting a ton of code. It most likely more cost-effective to just rewrite your app in a different style using requests and templates.
It looks as though this is probably something that we'll see more an more of as we go forward in the world of server-side JS.
I might have a play with writing something myself, however as commenter (on the OP) juandopazo mentions, this is possible already with YUI3.
Douglas Crockford mentions exactly what I'm on about (and YUI's cabailities) in this video on 'Serversideness' - see from 03:45.

Categories

Resources