Using node.js as a simple web server

后端 未结 30 2242
感情败类
感情败类 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条回答
  •  旧时难觅i
    2020-11-22 03:27

    You don't need express. You don't need connect. Node.js does http NATIVELY. All you need to do is return a file dependent on the request:

    var http = require('http')
    var url = require('url')
    var fs = require('fs')
    
    http.createServer(function (request, response) {
        var requestUrl = url.parse(request.url)    
        response.writeHead(200)
        fs.createReadStream(requestUrl.pathname).pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync) 
    }).listen(9615)    
    

    A more full example that ensures requests can't access files underneath a base-directory, and does proper error handling:

    var http = require('http')
    var url = require('url')
    var fs = require('fs')
    var path = require('path')
    var baseDirectory = __dirname   // or whatever base directory you want
    
    var port = 9615
    
    http.createServer(function (request, response) {
        try {
            var requestUrl = url.parse(request.url)
    
            // need to use path.normalize so people can't access directories underneath baseDirectory
            var fsPath = baseDirectory+path.normalize(requestUrl.pathname)
    
            var fileStream = fs.createReadStream(fsPath)
            fileStream.pipe(response)
            fileStream.on('open', function() {
                 response.writeHead(200)
            })
            fileStream.on('error',function(e) {
                 response.writeHead(404)     // assume the file doesn't exist
                 response.end()
            })
       } catch(e) {
            response.writeHead(500)
            response.end()     // end the response so browsers don't hang
            console.log(e.stack)
       }
    }).listen(port)
    
    console.log("listening on port "+port)
    

提交回复
热议问题