简体   繁体   English

在node.js中运行页面特定的Javascript

[英]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. 仪表板主页面是一个非常整洁的Web应用程序,它广泛使用了javascript和ajax。 The server currently runs apache and uses php; 服务器当前运行apache并使用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). 但是,我计划安装node.js并更新服务器端脚本以支持websocket(并且我也喜欢在服务器端和客户端使用javascript的想法)。

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? 有没有一种简单的方法可以像使用PHP一样在网站页面上运行特定于页面的JavaScript? 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. 我遇到过模板(例如使用胡须),但是当要提供特定文件时,我不明白是否有可能在服务器上运行javascript的特定模块。

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). 如果您使用Express之类的框架,则可以“拦截”(或称为“路由”)请求特定的URL,并运行服务器端JS处理该URL(包括在处理结束时呈现并返回模板)。 。

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). 与PHP的区别之一是PHP经常将模板和代码混合到一个文件中,而对于Node,这两个通常是分开的(因此,代码和布局之间有明显的分开)。

You should be looking into web frameworks for Node.js that help you with this kind of thing. 您应该研究Node.js的Web框架,以帮助您完成此类事情。 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. Express允许您将“路由”映射到处理程序,并且该处理程序可以位于所需的任何文件中。 Eg, 例如,

app.get('/energy/page-x', require('./routes/page-x-handler'));

Where ./routes/page-x-handler.js is something like: 其中./routes/page-x-handler.js类似于:

module.exports = function (req, res, next) {
    res.render('template-name');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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