Node.js查看源代码中断文件系统模块

时间:2018-04-07 16:12:05

标签: javascript node.js view-source

我正在尝试在node.js中创建一个Web服务器,但我遇到了一个奇怪的问题。

服务器正确响应查看页面的请求,但是当我在某些浏览器上查看页面源时,节点服务器会抛出错误

fs.js:379
  binding.open(pathModule.toNamespacedPath(path),
          ^

TypeError: path must be a string or Buffer
    at Object.fs.readFile (fs.js:379:11)
    at Server.<anonymous> (/ProjectFolder/index.js:32:6)
    at Server.emit (events.js:180:13)
    at parserOnIncoming (_http_server.js:642:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)

我想,也许查看源的请求有一个奇怪的请求路径,但是a)它说TypeError,所以它会在resolveFileName函数中出错。并且b)视图源不会在客户端以不同方式显示请求结果,而不对请求进行任何更改?

Google chrome: Error
MS Edge: OK
Internet Explorer: Error
Netscape 8: OK

这是我的代码:

文件系统:

> ProjectFolder
| > index.js
| > svrpath
| | > file.html

index.js:

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

function resolveFileName(req){
  var typs = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript"
  };
  if(req === "/"){
    return {
      fname: "./svrpath/file.html",
      type: "text/html"
    };
  }else if(/^.*\.(html|css|js)$/.test(req)){
    return {
      fname: "./svrpath" + req,
      type: typs[req.replace(/^.*(?=\.(html|css|js)$)/, "")]
    };
  }else if(/^.*\/$/.test(req)){
    return {
      fname:"./svrpath" + req.replace(/\/$/, "") + ".html",
      type: "text/html"
    };
  }else{
    return "error400";
  }
}

http.createServer(function(req, res){
  var file = resolveFileName(req.url);
  fs.readFile(file.fname, function(err, data){
    if(err){
      throw err;
    }
    res.writeHead(200, {"Content-Type": file.type});
    res.end(data);
  });
}).listen();

svrpath / file.html

<!DOCTYPE html>
<html>
  <body>
    <p>Hello World!</p>
    <p>Some more content</p>
  </body>
</html>

Working Example

1 个答案:

答案 0 :(得分:2)

您的浏览器默认询问favicon.ico,您没有答案,这就是为什么您有未定义的路径(没有这种情况)。您可以添加文件favicon.ico并为其创建条件:

function resolveFileName(req){
  var typs = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript"
  };
  if(req === "/"){
    return {
      fname: "./svrpath/file.html",
      type: "text/html"
    };
  }else if(/^.*\.(html|css|js)$/.test(req)){
    return {
      fname: "./svrpath" + req,
      type: typs[req.replace(/^.*(?=\.(html|css|js)$)/, "")]
    };
  }else if(/^.*\/$/.test(req)){
    return {
      fname:"./svrpath" + req.replace(/\/$/, "") + ".html",
      type: "text/html"
    };
  }else if(req === "/favicon.ico"){
      return {
        fname: "./svrpath/favicon.ico",
        type: "image/x-icon"
      }
  }else{
    return "error400";
  }
}