Loading basic HTML in Node.js

后端 未结 20 1352
暗喜
暗喜 2020-11-28 17:34

I\'m trying to find out how to load and render a basic HTML file so I don\'t have to write code like:

response.write(\'...

blahblahblah

...\
20条回答
  •  爱一瞬间的悲伤
    2020-11-28 18:01

    This would probably be some what better since you will be streaming the file(s) rather than loading it all into memory like fs.readFile.

    var http = require('http');
    var fs = require('fs');
    var path = require('path');
    var ext = /[\w\d_-]+\.[\w\d]+$/;
    
    http.createServer(function(req, res){
        if (req.url === '/') {
            res.writeHead(200, {'Content-Type': 'text/html'});
            fs.createReadStream('index.html').pipe(res);
        } else if (ext.test(req.url)) {
            fs.exists(path.join(__dirname, req.url), function (exists) {
                if (exists) {
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    fs.createReadStream('index.html').pipe(res);
                } else {
                    res.writeHead(404, {'Content-Type': 'text/html'});
                    fs.createReadStream('404.html').pipe(res);
            });
        } else {
            //  add a RESTful service
        }
    }).listen(8000);
    

提交回复
热议问题