作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 NodeJS 中有以下代码片段。该代码来 self 正在编写的教程,但是希望您重点关注 else if(req.url === "/"){...}
中的代码,因为这是我的问题发生的地方。在此代码中,我使用 readStream
来获取 HTML 文件的内容,并使用 pipe
将这些内容发送到客户端的套接字地址。
所以,我在这里遇到的困难是想要使用流来替换 HTML 文件中的 {title}
,并使用 NodeJS 中的 title
变量文件。
我知道您可以通过readFileSync
同步执行此操作,但我想尝试使用流,我知道它可以异步工作并且是 NodeJS 的最佳实践。
因此,由于我缺乏理解,我不确定如何使用流来执行此操作的正确方法,感谢任何帮助!
'use strict'
var http = require('http'),
fs = require('fs'),
html = "",
title = "Hello World", // <-- template text
obj = {
firstName: 'John',
lastName: 'Doe'
};
http.createServer(function(req, res){
if(req.url === '/api'){
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(obj));
}
else if(req.url === "/"){
res.writeHead(200, {'Content-Type': 'text/html'});
html = fs.createReadStream(__dirname + '/index.html');
html.on('data', function(data){ // <-- here I try to use the template text
data = data.toString().replace('{title}', title);
console.log(data);
});
html.pipe(res);
}
else {
// Accessing a URL not handled or specified above
res.writeHead(404);
res.end();
}
}).listen(1337, '127.0.0.1');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Learning NodeJS</title>
</head>
<body>
<h1>{title}</h1>
</body>
</html>
编辑:目前此代码不会将 HTML 中的 {title}
替换为 Hello World
。我已经重新启动了 NodeJS 服务器,以确保这不是我的代码未正确刷新的简单情况。
免责声明:我正在学习 NodeJS,请友善:)
最佳答案
修改“数据”事件处理函数中的局部变量不会更改响应中发送的数据。
代替管道,在“data”事件处理函数中写入数据,并在“end”事件处理函数中结束响应。
只是修改了一点
html.on('data', function(data) { // <-- here I try to use the template text
data = data.toString().replace('{title}', title);
console.log(data);
res.write(data);
});
html.on('end', function(data) {
res.end();
});
//html.pipe(res);
关于javascript - NodeJS 如何用 Stream 替换客户端模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35730080/
我是一名优秀的程序员,十分优秀!