Search code examples
node.jsiorollupjssveltesapper

How to open and read a file in Sapper/Svelte


I'm trying to open and read a directory of .md files in my Sapper app. I tried import but it doesn't allow for string expressions (`file${index}.md`). So I tried to open and read a file through fs node module but I get this messages in the server:

preferring built-in module 'fs' over local alternative at 'fs', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning preferring built-in module 'fs' over local alternative at 'fs', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning 'fs' is imported by src/routes/blog/[slug].svelte, but could not be resolved – treating it as an external dependency 'default' is imported from external module 'fs' but never used


Solution

  • If you're accessing the filesystem, you should be doing it in a server route — i.e. a .js file, like routes/blog/[slug].json.js (which would correspond to /blog/:slug.json) — not in a page, which will run on both the server and client.

    https://sapper.svelte.dev/docs#Server_routes