【问题标题】:fs.readFile() returns undefined [duplicate]fs.readFile() 返回未定义 [重复]
【发布时间】:2020-06-16 04:06:42
【问题描述】:

我正在尝试显示一个创建节点 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'
}

两个文件在同一个目录

【问题讨论】:

  • 尝试使用绝对 URL,我不确定 fs 模块是否接受相对路径作为有效参数
  • 你能显示你的文件夹结构吗
  • 绝对路径也不行
  • 文件夹 > index.js 和 page.html
  • 虽然我不认为你只是给出相对路径有什么问题,仅供参考stackoverflow.com/questions/33342984/…

标签: html node.js


【解决方案1】:

首先,fs.readFile 是异步函数。这意味着不会立即返回答案或阻止线程等待答案。相反,它需要一个回调来让您知道答案何时准备就绪。

其次,我建议使用path模块将__dirname(当前模块的目录名)和文件名合并成绝对文件路径。

我将使用不同的方法提供 3 种解决方案。

方案一、使用回调方法

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. 使用 .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);

【讨论】:

    猜你喜欢
    • 2021-01-01
    • 2019-10-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2015-12-26
    • 2012-07-06
    相关资源
    最近更新 更多