Using node.js as a simple web server

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

    The simpler version which I've came across is as following. For education purposes, it is best, because it does not use any abstract libraries.

    var http = require('http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');
    
    var mimeTypes = {
      "html": "text/html",
      "mp3":"audio/mpeg",
      "mp4":"video/mp4",
      "jpeg": "image/jpeg",
      "jpg": "image/jpeg",
      "png": "image/png",
      "js": "text/javascript",
      "css": "text/css"};
    
    http.createServer(function(req, res) {
        var uri = url.parse(req.url).pathname;
        var filename = path.join(process.cwd(), uri);
        fs.exists(filename, function(exists) {
            if(!exists) {
                console.log("not exists: " + filename);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.write('404 Not Found\n');
                res.end();
                return;
            }
            var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
            res.writeHead(200, {'Content-Type':mimeType});
    
            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(res);
    
        }); //end path.exists
    }).listen(1337);
    

    Now go to browser and open following:

    http://127.0.0.1/image.jpg
    

    Here image.jpg should be in same directory as this file. Hope this helps someone :)

提交回复
热议问题