nodejs作为web服务器使用太多的if条件来提供静态文件



我只是想知道如果它是正常的,当使用香草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

正常吗?是否有任何方法来解决这个问题,使用原始节点JS?如果没有,你会推荐什么?

谢谢。

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

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