DEV Community

Discussion on: Adventures of a Hobbyist ~ Part seven

Collapse
 
avalander profile image
Avalander • Edited

Great progress, I enjoy reading these posts!

Though if you want to tell me some ways you'd have solved them I'd love to hear them.

Glad you asked!

If I try and browser to http://localhost/home?beta=true I'll get a 404

Since you're not using the query string at all, the easiest is to simply ignore it. You can use node's url module to parse the url and get the path and query string separately.

const url = require('url')
const path = require('path')
...
function router(request_url) {
    const address = url.parse(request_url).pathname // get only the path of the url, without host or query
        .replace(/\/$/, '') || 'index' // remove the trailing slash, should there be any. Use 'index' if the path is empty
    try {
        const filepath = path.join(__dirname, pages, ...address.split('/'))
        return fs.readFileSync(`${filepath}.html`, 'utf8')
    } catch (err) {
        ...
    }
}

Incidentally, this would also address the other limitation you mention. Using url.parse(...).pathname will get you the full path without the host or the query string, so you can use that to read the correct file.

path.join(pages, ...address.split('/')) will basically return the right file path in any OS, it will append the pages folder to the file's folder (__dirname is the folder where your source file is located) and then replace all slashes in the url path with the OS character to separate folders.