Using node.js as a simple web server

后端 未结 30 2223
感情败类
感情败类 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:22

    I found a interesting library on npm that might be of some use to you. It's called mime(npm install mime or https://github.com/broofa/node-mime) and it can determine the mime type of a file. Here's an example of a webserver I wrote using it:

    var mime = require("mime"),http = require("http"),fs = require("fs");
    http.createServer(function (req, resp) {
    path  = unescape(__dirname + req.url)
    var code = 200
     if(fs.existsSync(path)) {
        if(fs.lstatSync(path).isDirectory()) {
            if(fs.existsSync(path+"index.html")) {
            path += "index.html"
            } else {
                code = 403
                resp.writeHead(code, {"Content-Type": "text/plain"});
                resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
            }
        }
        resp.writeHead(code, {"Content-Type": mime.lookup(path)})
        fs.readFile(path, function (e, r) {
        resp.end(r);
    
    })
    } else {
        code = 404
        resp.writeHead(code, {"Content-Type":"text/plain"});
        resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
    }
    console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
    }).listen(9000,"localhost");
    console.log("Listening at http://localhost:9000")
    

    This will serve any regular text or image file (.html, .css, .js, .pdf, .jpg, .png, .m4a and .mp3 are the extensions I've tested, but it theory it should work for everything)

    Developer Notes

    Here is an example of output that I got with it:

    Listening at http://localhost:9000
    GET 200 OK /cloud
    GET 404 Not Found /cloud/favicon.ico
    GET 200 OK /cloud/icon.png
    GET 200 OK /
    GET 200 OK /501.png
    GET 200 OK /cloud/manifest.json
    GET 200 OK /config.log
    GET 200 OK /export1.png
    GET 200 OK /Chrome3DGlasses.pdf
    GET 200 OK /cloud
    GET 200 OK /-1
    GET 200 OK /Delta-Vs_for_inner_Solar_System.svg
    

    Notice the unescape function in the path construction. This is to allow for filenames with spaces and encoded characters.

提交回复
热议问题