如何设置一个nodejs服务器,通过检查url来为客户端提供正确的文件?

我正在尝试编写一个节点js服务器,如果资源位于文件系统中,则可以返回用户请求的任何内容。

例如,如果请求URL是/index.html ,它会尝试在根目录中find一个名为“index.html”的文件,并用一个stream来响应该文件。 如果请求是/myscript.js ,它会做同样的事情,find一个名为myscript.js的文件,并将其传递给响应。

这是我到目前为止:

 var http = require("http"); var fs = require("fs"); var port = process.env.PORT || 3000; http.createServer(function (request, response) { if (request.method == "GET") { console.log(request.url); if (request.url == "/") { // if the url is "/", respond with the home page response.writeHead(200, {"Content-Type": "text/html"}); fs.createReadStream("index.html").pipe(response); } else if (fs.existsSync("." + request.url)) { response.writeHead(200/*, {"Content-Type": request.headers['content-type']}*/); fs.createReadStream("." + request.url).pipe(response); } else { response.writeHead(404, {"Content-Type": "text/plain"}); response.end("404 Not Found"); } } else { response.writeHead(404, {"Content-Type": "text/plain"}); response.end("404 Not Found"); } }).listen(port); // Console will print the message console.log('Server running at http://127.0.0.1:' + port +'/'); 

有几件事我不喜欢这个代码:

  • 显然fs认为每当path以/开始,文件不存在,所以我必须添加一个. 之前的文件path。 见第10和12行。这会一直工作吗? 我觉得这是一个非常糟糕的技巧来解决这个问题。
  • 我不知道请求文件的内容types(第11行)。 我在网上search,发现很多方法来做到这一点与其他模块,我必须使用npm安装。 节点中是否有东西可以找出内容types?

解决你的两个要点:

  • 这是有道理的,你会需要一个. 当使用fsfs会查看系统的根目录。 请记住,系统根目录与您的服务器根目录不同。
  • 一个想法是使用path.extname ,然后使用switch语句来设置内容types。

下面的代码是从我写的关于如何使用无Express的Node来设置一个简单的静态服务器的博客文章中获得的:

 let filePath = `.${request.url}`; // ./path/to/file.ext let ext = path.extname(filePath); // .ext let contentType = 'application/octet-stream'; // default content type if(ext === '') { filePath = './index.html'; // serve index.html ext = '.html'; } switch (ext) { case '.html': contentType = 'text/html'; break; case '.css': contentType = 'text/css'; break; case 'js': contentType = 'text/javascript'; }