【问题标题】:node js as a webserver using too much if conditions to server static files节点 js 作为网络服务器使用过多的 if 条件来服务器静态文件
【发布时间】:2021-10-17 00:37:55
【问题描述】:

我只是想知道在使用 vanilla nodejs 服务静态文件时使用大量else if 的语句是否正常:

const server = http.createServer(function(req, res) {
if (req.url == '/') {
    
    res.writeHead(307,{'Location': '/index.html'});
    res.end();
} else if (req.url == '/index.html') { 
    fs.readFile('index.html', function(error, data) {
    if (error) {
        res.writeHead(404, { 'Content-Type': 'text/html' })
        res.write('<p>File could not be readed.</p>')
        
        
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        res.write(data)
        
        
    }
    res.end()
})} else if (req.url == "/solutions.html") {
    
    fs.readFile('solutions.html', function(error, data) {
    if (error) {
        res.writeHead(404, { 'Content-Type': 'text/html'})
        res.write('<p>File could not be readed.</p>')
        
        
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html'})
        res.write(data)
        
    }
    res.end()
})} else if (req.url == "/solutions/antoher-subpage.html") {
    res.writeHead(200, {'Content-Type': 'text/html'})
    res.write('0.1')
    res.end()
}

上面的模型是我用来提供静态文件的模型,但是随着页面的增长我需要为我想要添加的每个页面添加一个else if

这正常吗?有没有办法通过使用原始 Node JS 来解决这个问题?如果没有,你会推荐什么?

谢谢。

【问题讨论】:

    标签: node.js http if-statement


    【解决方案1】:

    如果你只需要一个静态 HTTP 服务器,使用 nginx 会比 Node.js 快得多

    如果您需要静态文件服务和一些请求处理,请考虑使用expressserve-static

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      相关资源
      最近更新 更多