Joshua Bambrick
Joshua Bambrick

Reputation: 2699

Running Page Specific Javascript in node.js

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.

Upvotes: 0

Views: 169

Answers (2)

jmar777
jmar777

Reputation: 39649

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');
}

Upvotes: 2

robertklep
robertklep

Reputation: 203231

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).

Upvotes: 2

Related Questions