Loading basic HTML in Node.js

后端 未结 20 1375
暗喜
暗喜 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

    I know this is an old question - here is a simple file server utility if you'd prefer to not use connect or express; but rather the http module.

    var fileServer = require('./fileServer');
    var http = require('http');
    http.createServer(function(req, res) {
       var file = __dirname + req.url;
       if(req.url === '/') {
           // serve index.html on root 
           file = __dirname + 'index.html'
       }
       // serve all other files echoed by index.html e.g. style.css
       // callback is optional
       fileServer(file, req, res, callback);
    
    })
    module.exports = function(file, req, res, callback) {
        var fs = require('fs')
            , ext = require('path').extname(file)
            , type = ''
            , fileExtensions = {
                'html':'text/html',
                'css':'text/css',
                'js':'text/javascript',
                'json':'application/json',
                'png':'image/png',
                'jpg':'image/jpg',
                'wav':'audio/wav'
            }
        console.log('req    '+req.url)
        for(var i in fileExtensions) {
           if(ext === i) {    
              type = fileExtensions[i]
              break
           }
        }
        fs.exists(file, function(exists) {
           if(exists) {
              res.writeHead(200, { 'Content-Type': type })
              fs.createReadStream(file).pipe(res)
              console.log('served  '+req.url)
              if(callback !== undefined) callback()
           } else {
              console.log(file,'file dne')
             }  
        })
    }
    

提交回复
热议问题