How to use file apis with sveltekit netlify

Viewed 397

I have code like this

import fs from 'fs';
import { promisify } from 'util';
import type { SvelteComponent } from 'svelte';

const readdir = promisify(fs.readdir);

export async function getAllPosts() {
    const files = (await readdir(`src/data/posts`)).map((i) => i.replace(/.svx$/, ''));
    return files;
}

and my server route

import { getAllPosts } from '../../lib/blog';

export async function get() {
    return { body: await getAllPosts() };
}

and it works fine in development, but it doesn't work in production on netlify, because there isn't really a src/data/posts directory anymore. How can I get sveltekit to generate this array at buildtime?

I have tried using the static adaptor but it doesn't generate the routes properly becuase although there are links to all the pages on the site, they aren't generated right away. So I think I have to go with the netlify adapter.

1 Answers

You are correct that the /src/data/posts folder does not exists anymore and thus your code does not work.

The first thing you have to do is to copy your assets to the /functions folder so that they are available in the first place.

Then you have to make sure your script looks in the correct place, here there is some magic going on with the function not being executed in the same location as it is placed. You can read more on this on the Netlify support forums, in a topic like this one.

If you finally find a working solution maybe add it here as an answer as well.

Related