javascript - 为什么 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 更多字节>
解决方案
因为这就是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) {
//
});
推荐阅读
- php - 显示两个价目表之间的差异
- c++ - colPivHouseholderQr().solve 拟合的相关性
- javascript - 遍历对象Javascript的对象?
- lua - string.len() 总是返回错误“意外符号”
- r - 如何使用 R 求条件均值
- node.js - 调用返回 AsyncIterableIterator 而不使用“for await”块的函数
- reactjs - 在 VS Code 中反应原生工具。调试控制台中没有任何内容
- linux - 通过 Windows Powershell 对 Linux 服务器执行 Linux 命令
- javascript - JS 中的主题切换器
- c++ - 混合功能是一种不好的做法吗
与其他课程?