首页 > 解决方案 > 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'
}

这两个文件在同一个目录中

标签: htmlnode.js

解决方案


首先,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);

推荐阅读