I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.

Here is an excerpt from my directory structure:

|- index.md
|- services.txt
|- about
   |- index.md
   |- technologies.html
|- index.html
|- services.html
|- section-[section].json.js
|- about
   |- index.html
   |- technologies.html

I've made JSON interface section-[section].json.js that is used to request content. The content of sectionX can be in file content/sectionX.ext with whatever extension and the content is also parsed through marked if it's a .md file.

This is how I am loading the content in my routes/services.html:

export default {
    preload() {
        return this.fetch('section-services.json').then(r => r.json()).then(section => {
            return {section};

Nested files are requested using dot notation, i.e. about.technologies could be resolved either to file content/about/technologies.ext or content/about/technologies/index.ext (similar to how sapper resolves URIs to files).

The part that I would like to have reviewed is my routes/section-[section].json.js. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.

import fs from 'fs'
import path from 'path'
import marked from 'marked'

function getFileFromDir(file, directory)
    const filesInDir = fs.readdirSync('content/'+directory, {withFileTypes: true})
                        .filter(f => f.isFile() && file == path.parse(f.name).name)

    if (filesInDir.length)
        let fileName = 'content/'

        if (directory.length)
            fileName += directory + '/'

        fileName += filesInDir[0].name

        return fileName

    return null

function getFile(path) 
    path = path.split('.')

    // First try to get the named file
    let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
    if (file)
        return file

    // Assume that path is a directory and look for index
    file = getFileFromDir('index', path.join('/'))
    if (file)
        return file

    return null

export function get(req, res) {
    let file = getFile(req.params.section)

    if (!file)
        return 'Failed to fetch content of section ' + req.params.section

    let content = fs.readFileSync(file, 'utf8')

    if ('.md' == path.extname(file))
        content = marked(content)

    res.writeHead(200, {
        'Content-Type': 'application/json',
        'Cache-Control': `max-age=${30 * 60 * 1e3}`

    content = JSON.stringify({content})


My experience with Node is also fairly limited, all tips are appreciated!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.