尝试运行 Node http 服务器时出现绑定错误

Getting a binding error when trying to run Node http server

我们应该创建一个简单的 http 节点服务器,该服务器应使用名为 index.html 的文件响应根 url 请求。不要使用 ExpressJS。代码应该有错误检查和至少一个回调。在 index.html 中放置五个或更多 html 个元素。其中一个元素应该是 link 到外部页面。

这是我的代码:

var http = require("http");
var fs   = require('fs');
var index = fs.readFileSync('index.html');


var server = http.createServer(function(request, response) {

fs.exists(index, function(exists) {
     try {
       if(exists) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<html>");
  response.write("<head>");
  response.write("<title>Hello World!</title>");
  response.write("</head>");
  response.write("<body>");
  response.write("<div>");
  response.write("Hello World!");
  response.write("</div>");
  response.write("<a href='http://www.google.com' target='_blank'>Google</a>")
  response.write("</body>");
  response.write("</html>");
        } else {
         response.writeHead(500);
        }
    } finally {
         response.end(index);
    }
 });
});
 
server.listen(80);
console.log("Server is listening");

我遇到了这个绑定错误:

服务器正在侦听

fs.js:166
  binding.stat(pathModule._makeLong(path), cb);
          ^
TypeError: path must be a string
    at Object.fs.exists (fs.js:166:11)
    at Server.<anonymous> (/Users/rahulsharma/Desktop/server.js:8:4)
    at Server.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2112:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
    at Socket.socket.ondata (http.js:1970:22)
    at TCP.onread (net.js:527:27)

有什么想法吗?

将 index.html 与 .js 文件放在一起。将所有 html 放入该文件。

var http = require("http");
var fs   = require('fs');

var server = http.createServer(function(req, res) {
    fs.readFile("index.html",function(err,content){
        if(err){
            throw err;
            console.log("Error reading index file.");
            res.send("Aw snap!");
        }
        else{
            res.writeHead(200,{"Content-type":"text/HTML"});
            res.end(content,"UTF-8");
        }
    });
});
server.listen(80);

根据您的堆栈跟踪,错误在这一行内:

fs.exists(index, function(exists)

您传递给此函数(检查给定文件是否存在)的实际上是文件的内容。您应该作为第一个参数传递的可能是 "index.html" 而不是 index 变量

您正在尝试调用 fs.exists,它需要一个字符串路径,并且您正在为它提供一个文件处理程序索引。 这就是为什么错误是:

path must be a string

要么尝试使用字符串 "index.html" 并且不要在那里同步读取它。在存在的回调中异步执行

fs.exists("index.htm", function(){ fs.readFile("index.htm")

将索引变量替换为 'index.html' 即可,但

请不要使用 fs.exists ,请阅读其 API 文档 http://nodejs.org/api/fs.html#fs_fs_exists_path_callback