[英]How do I run a Node.js script in my HTML page, as I do with PHP?
自2010年以来,我一直是一名PHP开发人员。我喜欢PHP,只是因为它很简单。 但是我想了解更多有关Node.js的信息。 它看起来很有趣,特别是因为我知道JavaScript并且我非常喜欢它。
有谁知道我如何像HTML一样在HTML页面中运行Node.js脚本而不显示源代码? 这样真的有效吗?
我看过许多教程,它们在终端中执行Node.js,但是我没有找到在简单的HTML页面中运行Node.js的快速方法。
谢谢! :)
您似乎正在混淆PHP的两个不同功能:
如果您使用的是Node.js,则通常:
从Node.js主页引用:
一个例子:Web服务器
用Node编写的这个简单的Web服务器对每个请求都响应“ Hello World”。
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
要运行服务器,请将代码放入文件example.js中,并使用节点程序从命令行执行它:
% node example.js Server running at http://127.0.0.1:1337/
这是一个简单的TCP服务器的示例,该服务器侦听端口1337并回显您发送的任何内容:
var net = require('net'); var server = net.createServer(function (socket) { socket.write('Echo server\\r\\n'); socket.pipe(socket); }); server.listen(1337, '127.0.0.1');
您一直在编写的php代码可能只是php的html模板版本(由于缺少更好的术语...)
当浏览器中请求.php页面时,将调用一个php解释器,该解释器将解析html中的php标签并将其替换为html / text。 然后将该结果发送到浏览器。
node.js不能那样工作。
Node.js还有很多……。在涉及这个特定主题时,比php更为冗长。 node.js不仅是Web应用程序框架或Web服务器,而且还是FAR,它还可以用作各种可执行文件来运行常见任务。
通常,要获得在node.js中寻找的功能,可以使用模板框架(如把手和express)来处理Web服务器和路由。 这是一个例子:
// this is just an example, it may or may not work, I did not test it.
var express = require('express'),
app = express(),
exphbs = require('express-handlebars'),
hbs,
path = require('path');
// serve all files under the /assets folder as static files
app.use('/assets', express.static(path.join(__dirname, '/assets')));
// handlebar engine config
hbs = exphbs.create({
defaultLayout: 'main'
});
// attach engine and specify view location
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, '/views'));
// home page http://domain.com/
app.get('/', function (req, resp) {
resp.render('home', {title: 'Home | Hello World!', text: 'Welcome to my site!'});
});
// start webserver
app.listen(3000);
上面的节点应用程序将创建一个侦听端口3000的Web服务器,该服务器响应对/assets
和/
请求。 当请求/
,将使用/views/layouts
的main.handlebars
布局来呈现/views
文件夹中的home.handlebars
视图。这是一个示例视图,将显示为上面创建的/
路由传递的标题:
/views/layouts/main.handlebars
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
/views/home.handlebars
<h1>Hello World!</h1>
<p>{{text}}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.