2015-01-08 44 views
0

我们应该创建一个简单的http节点服务器,该服务器应该使用名为index.html的文件响应root-url请求。不要使用ExpressJS。代码应该有错误检查和至少一个回调。在您的index.html中放入五个或更多html元素。其中一个元素应该是到外部页面的链接。尝试运行时出现绑定错误节点http服务器

这是我的代码有:

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) 

有什么想法?

回答

0

与“index.html的”更换指标变量将做的工作,但

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

+0

感谢这一点,但我有点糊涂 - 是不是fs.exists用于测试文件路径是否正确?通过API阅读,没有任何其他的建议? –

+0

在节点中,当文件不存在时,程序不会给出错误,实际上它将变量设置为undefined。因此,如果索引设置为undefined,那么在使用fs.readFileSync()读取文件时,它不存在,否则您就知道该怎么做。 – pratiklodha

0

将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); 
0

根据您堆栈跟踪误差在这一行内:

fs.exists(index, function(exists) 

传递给这个函数(检查是否给定的文件存在)什么是真正的文件内容。你应该通过的第一个参数可能是"index.html"而不是index变量

0

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

path must be a string 

可尝试使用字符串“的index.html”,不读它同步出现。做到这一点异步的存在回调

fs.exists("index.htm", function(){ fs.readFile("index.htm") 
相关问题