gpt4 book ai didi

javascript - NodeJS 如何用 Stream 替换客户端模板

转载 作者:行者123 更新时间:2023-12-03 07:33:09 28 4
gpt4 key购买 nike

我在 NodeJS 中有以下代码片段。该代码来 self 正在编写的教程,但是希望您重点关注 else if(req.url === "/"){...} 中的代码,因为这是我的问题发生的地方。在此代码中,我使用 readStream 来获取 HTML 文件的内容,并使用 pipe 将这些内容发送到客户端的套接字地址。

所以,我在这里遇到的困难是想要使用流来替换 HTML 文件中的 {title} ,并使用 NodeJS 中的 title 变量文件。

我知道您可以通过readFileSync同步执行此操作,但我想尝试使用流,我知道它可以异步工作并且是 NodeJS 的最佳实践。

因此,由于我缺乏理解,我不确定如何使用流来执行此操作的正确方法,感谢任何帮助!

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

HTML

<!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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com