samedi 16 octobre 2021

node js as a webserver using too much if conditions to server static files

I was just wondering if it is normal that when using vanilla nodejs to server static files a lot of else if's statements are used:

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()
}

The model above is the one that I am following to serve static files, but as the page grows I need to add one else if for every page that I want to add.

Is this normal? Is there any way of solving this by using raw Node JS? If not, what would you recommend?

Thanks.

Aucun commentaire:

Enregistrer un commentaire