allesman
allesman

Reputation: 47

Get path to read file from /static (SvelteKit)

I have a file "artists.csv" which i need to read during execution of my server side code (when an API request is made, to be specific).

new Promise((resolve, reject) => {
    fs.createReadStream(artistsFilePath)
        ...
});

I have made the assumption the static folder is the correct place to put such a file. So now I need the path for the file in the static folder. In the html frontend %sveltekit.assets%/favicon.png is used but this does not work in my case. The only way I found to make it work in dev as well as prod is this piece of spaghetti:

const __dirname = dirname(fileURLToPath(import.meta.url));
let artistsFilePath = __dirname + '/../../../../../client/artists.csv';
if (!fs.existsSync(artistsFilePath)) {
    // Development mode
    artistsFilePath = __dirname + '/../../static/artists.csv';
}

Surely there is a better way to do this?

Upvotes: 1

Views: 18

Answers (1)

brunnerh
brunnerh

Reputation: 185280

Import the file.

import artists from '../some/path/artists.csv?raw';

Using ?raw imports the file as string.

static should only be used for things that require a fixed path, like the icon, a robots.txt, etc. Everything else should be done via imports, this also ensures that the asset can be cached properly if accessed by the browser (a hash will be added to the path when importing assets as URL).

Upvotes: 1

Related Questions