Using node.js as a simple web server

后端 未结 30 2234
感情败类
感情败类 2020-11-22 02:54

I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same

30条回答
  •  鱼传尺愫
    2020-11-22 03:10

    Check out this gist. I'm reproducing it here for reference, but the gist has been regularly updated.

    Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument.

    var http = require("http"),
        url = require("url"),
        path = require("path"),
        fs = require("fs"),
        port = process.argv[2] || 8888;
    
    http.createServer(function(request, response) {
    
      var uri = url.parse(request.url).pathname
        , filename = path.join(process.cwd(), uri);
    
      fs.exists(filename, function(exists) {
        if(!exists) {
          response.writeHead(404, {"Content-Type": "text/plain"});
          response.write("404 Not Found\n");
          response.end();
          return;
        }
    
        if (fs.statSync(filename).isDirectory()) filename += '/index.html';
    
        fs.readFile(filename, "binary", function(err, file) {
          if(err) {        
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(err + "\n");
            response.end();
            return;
          }
    
          response.writeHead(200);
          response.write(file, "binary");
          response.end();
        });
      });
    }).listen(parseInt(port, 10));
    
    console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");
    

    Update

    The gist does handle css and js files. I've used it myself. Using read/write in "binary" mode isn't a problem. That just means that the file isn't interpreted as text by the file library and is unrelated to content-type returned in the response.

    The problem with your code is you're always returning a content-type of "text/plain". The above code does not return any content-type, but if you're just using it for HTML, CSS, and JS, a browser can infer those just fine. No content-type is better than a wrong one.

    Normally the content-type is a configuration of your web server. So I'm sorry if this doesn't solve your problem, but it worked for me as a simple development server and thought it might help some other people. If you do need correct content-types in the response, you either need to explicitly define them as joeytwiddle has or use a library like Connect that has sensible defaults. The nice thing about this is that it's simple and self-contained (no dependencies).

    But I do feel your issue. So here is the combined solution.

    var http = require("http"),
        url = require("url"),
        path = require("path"),
        fs = require("fs")
        port = process.argv[2] || 8888;
    
    http.createServer(function(request, response) {
    
      var uri = url.parse(request.url).pathname
        , filename = path.join(process.cwd(), uri);
    
      var contentTypesByExtension = {
        '.html': "text/html",
        '.css':  "text/css",
        '.js':   "text/javascript"
      };
    
      fs.exists(filename, function(exists) {
        if(!exists) {
          response.writeHead(404, {"Content-Type": "text/plain"});
          response.write("404 Not Found\n");
          response.end();
          return;
        }
    
        if (fs.statSync(filename).isDirectory()) filename += '/index.html';
    
        fs.readFile(filename, "binary", function(err, file) {
          if(err) {        
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(err + "\n");
            response.end();
            return;
          }
    
          var headers = {};
          var contentType = contentTypesByExtension[path.extname(filename)];
          if (contentType) headers["Content-Type"] = contentType;
          response.writeHead(200, headers);
          response.write(file, "binary");
          response.end();
        });
      });
    }).listen(parseInt(port, 10));
    
    console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");
    

提交回复
热议问题