首页 > 解决方案 > 为什么 Node.js javascript 函数 res.write(data) 在我记录时输出数字?

问题描述

我在我的 Raspberry Pi 上使用 Node.js 来读取本地文件“test.html”,当我记录输出时,它看起来像是十六进制而不是 html。为什么是这样?另外,我知道 fs.readFile 仅适用于本地文件。我会用什么来读取像 'myzone.example.com/test.html' 这样的 URI?(提前感谢您的帮助。)

function handler (req, res) { //create server
  fs.readFile('../Public/test.html', function(err, data) { //read file index.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      console.log(err);
      return res.end("404 Not Found at Arcade.");
    }
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.write(data); 
    console.log("Page Data: ", data);
    return res.end();
  });
}

Console.log 输出:

页数据: <缓冲区 3c 21 64 6f 63 74 79 70 65 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 3e 0a 3c 68 65 61 64 3e 0a 3c 74 69 74 6c 65 3e 8d 79 4c 20 4 50 61 67 65 3c ... 69 更多字节>

标签: javascriptnode.jsraspberry-pi

解决方案


因为这就是fs.readFile工作原理。

来自https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback

如果未指定编码,则返回原始缓冲区。

所以这就是你得到的:原始缓冲区内容。

如果您希望内容为 UTF-8,那么您需要在使用时指定该编码fs.readFile

fs.readFile('../Public/test.html', 'utf8', function (err, data) {
  //
});

推荐阅读