简体   繁体   English

NodeJS 如何用流替换客户端模板

[英]NodeJS How to replace client side template with a Stream

I have the following snippet in NodeJS.我在 NodeJS 中有以下代码段。 The code is from a tutorial I am working on, however would like for you to focus on the code within the else if(req.url === "/"){...} since that is where my problem is occurring.该代码来自我正在研究的教程,但是希望您专注于else if(req.url === "/"){...}因为那是我的问题发生的地方。 In this code I am using a readStream to get the contents of my HTML file, and I am using pipe to send these contents to the client's socket address.在这段代码中,我使用readStream来获取我的 HTML 文件的内容,并且我使用pipe将这些内容发送到客户端的套接字地址。

So, what I am struggling with here is in wanting to use a stream to replace the {title} within my HTML file, with the title variable in my NodeJS file.所以,我在这里挣扎的是想要使用流来替换我的 HTML 文件中的{title} ,以及我的 NodeJS 文件中的title变量。

I know that you can do this synchronously via readFileSync but I want to try and use a stream, which I understand works asynchronously and is a best practice in NodeJS.我知道您可以通过readFileSync同步执行此操作,但我想尝试使用流,我理解它是异步工作的,并且是 NodeJS 中的最佳实践。

Thus due to my lack of understanding, I am not sure of the correct approach of how to use a stream to do this, any help is appreciated!因此,由于我缺乏理解,我不确定如何使用流来做到这一点的正确方法,任何帮助表示赞赏!

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 HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Learning NodeJS</title>
</head>
<body>
    <h1>{title}</h1>
</body>
</html>

EDIT : Right now this code does not replace the {title} in the HTML into Hello World .编辑:现在此代码不会将 HTML 中的{title}替换为Hello World I have re-started my NodeJS server to make sure this is not some simple case of my code not being refreshed properly.我重新启动了我的 NodeJS 服务器,以确保这不是我的代码没有正确刷新的简单情况。

Disclaimer: I am learning NodeJS, please be kind :)免责声明:我正在学习 NodeJS,请善待:)

modifying local variable in 'data' event handler function is not going to change the data being sent in response. 在“数据”事件处理程序函数中修改局部变量将不会更改作为响应发送的数据。

Instead of pipe, write the data in 'data' event handler function and end the response in 'end' event handler function. 代替管道,将数据写入“数据”事件处理函数中,并在“结束”事件处理函数中结束响应。

Just the modified bit 只是修改位

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

I suggest you use a template engine that perform streamed rendering. 我建议您使用执行流式渲染的模板引擎。 I think this , this and this are good places to start with. 我觉得这个这个这个是很好的地方开始。

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

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