让 node.js 读取 html 格式的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9749114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:20:50  来源:igfitidea点击:

Getting node.js to read files in html format

node.js

提问by Saif Bechan

I am developing a small app in Node.js. I am just using Node.js for input and output. The actual website is just running through nginx. The website has a Websocket connection with node.js and is primarily used for db manipulations.

我正在 Node.js 中开发一个小应用程序。我只是使用 Node.js 进行输入和输出。实际的网站只是通过 nginx 运行。该网站与 node.js 有 Websocket 连接,主要用于数据库操作。

One of the things I am trying to do is get node to send small pieces of html along with the data from the database. I tried the following code.

我正在尝试做的一件事是让节点发送小块 html 以及来自数据库的数据。我尝试了以下代码。

simplified:

简化:

    connection.on('message', function(message) {
        fs.readFile(__dirname + '/views/user.html', function(err, html){

            if(err){
                console.log(err);
            }else{
                connection.sendUTF( JSON.stringify({
                    content: html,
                    data: {}
                }));
            }
        });
    }
});

When I console.log(html)on the server or in the client I only get numbers back.

当我console.log(html)在服务器或客户端时,我只会得到数字。

Anyone know what could be wrong.

任何人都知道可能有什么问题。

NOTE:I really want to stay away from stuff like socket.io, express, etc. Just keeping it as simple as possible and no fallbacks are needed.

注意:我真的很想远离诸如socket.io,express等之类的东西。只要让它尽可能简单并且不需要回退。

回答by Sebastian Stumpf

If you don't specify an encoding for fs.readFile, you will retrieve the raw buffer instead of the expected file contents.

如果您没有为fs.readFile指定编码,您将检索原始缓冲区而不是预期的文件内容。

Try calling it this way:

尝试这样称呼它:

fs.readFile(__dirname + '/views/user.html', 'utf8', function(err, html){
....