html - fs.readFile() 返回未定义
问题描述
我正在尝试显示一个创建节点 http 服务器的 html 页面,当我尝试获取它返回未定义的 html 文件的代码时,这是代码...
var http = require('http');
var fileContent = function(path, format) {
var fs = require('fs');
fs.readFile(path, format, function(error, contents) {
if (error) throw error;
return contents;
});
}
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
page = fileContent('./page.html','utf8');
console.log(page);
res.end(page);
}).listen(8080);
我打印了错误,
[Error: ENOENT: no such file or directory, open './page.html'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: './page.html'
}
这两个文件在同一个目录中
解决方案
首先,fs.readFile
是异步函数。这意味着不会立即返回答案或阻止线程等待答案。相反,它需要一个回调来让您知道答案何时准备就绪。
其次,我建议使用path
模块合并__dirname
(当前模块的目录名)和文件名来制作绝对文件路径。
我将使用不同的方法提供 3 种解决方案。
解决方案1.使用回调方法
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileContent = function(path, format, cb) {
fs.readFile(path, format, function(error, contents) {
if (error) throw error;
cb(contents);
});
}
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fileContent(path.join(__dirname, 'page.html'), 'utf8', function (page) {
console.log(page);
res.end(page);
});
}).listen(8080);
解决方案 2. Promise 使用.then
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileContent = function(path, format) {
return new Promise(function (resolve, reject) {
fs.readFile(path, format, function(error, contents) {
if (error) reject(error);
else resolve(contents);
});
});
}
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fileContent(path.join(__dirname, 'page.html'), 'utf8')
.then(function(page) {
console.log(page);
res.end(page);
});
}).listen(8080);
解决方案 3. Promise 使用 async/await
var http = require('http');
var fs = require('fs');
var path = require('path');
var fileContent = function(path, format) {
return new Promise(function (resolve, reject) {
fs.readFile(path, format, function(error, contents) {
if (error) reject(error);
else resolve(contents);
});
});
}
var server = http.createServer(async function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var page = await fileContent(path.join(__dirname, 'page.html'), 'utf8');
console.log(page);
res.end(page);
}).listen(8080);
推荐阅读
- python - 训练pytorch的简单代码时,cpu比例增加。GPU 大约为 0%
- javascript - 为什么jquery将鼠标悬停在一个元素上,突出显示所有元素
- c++ - 如何优化 Cuda 内核性能?
- angular - 通过 @Input 构造组件选择器
- python - 每次下载 pip 都失败(找不到满足要求的版本**(来自版本:)找不到匹配的分发**)
- python - 如何在pyspark中对像A1、A2、A10这样的ID进行排序?
- javascript - 如何使用express在路由器内部调用restfull API
- android - 登录时出错 仍然提示但仍然登录
- c - 进程返回 -1073741819 <0xC0000005>
- assembly - 如何在 xtensa 架构中映射重置向量?