简体   繁体   中英

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.

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

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. Eg,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM