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

标签 javascript node.js

我在 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/

相关文章:

javascript - nodejs websocket 服务器中的内存泄漏

javascript - 使用 jQuery 构建的 ajax/json 提交图像文件

javascript - 在某些网站上停止和开始执行扩展

javascript - LDAP over TLS 在 Node 中使用 ldap-client

node.js - 如何设置nginx配置?

javascript - 如何为与 ASP .Net MVC 包装器一起使用的 Kendo UI 进行 TDD

javascript - 元素边框上的html鼠标悬停事件

javascript - 如何使用其他站点的登录信息发出 JavaScript 请求

node.js - Watson Concept-Insights 文档列表/限制选项在 NodeJS 中不起作用

windows - npm 安装 bower 挂起