I have a svelte project that basically is a database of links to internal or external files represented visually as a table. Nothing uber-fancy.
So, I’ve read in other post on StackOverflow that I have to implement a route in order to properly serve static files. I ended up with the following code that perfectly works locally: the execution reaches the code, correctly defines the path of the file and serves the file to browser
the code is put into /src/routes/[...path/+server.js]
file:
import path from 'node:path'
import fs from 'node:fs/promises'
import { error } from '@sveltejs/kit'
import { defineConfig } from 'vite';
export const GET = async ({ params }) => {
console.log("i've got the params ", params);
const workingFolder = import.meta.env.WORKING_DIR;
console.log("here is my url ", import.meta.url)
const pathName = `${workingFolder}/static${params.path}`;
console.log("here is the full path: ", pathName);
try {
const file = await fs.readFile(pathName);
return new Response(file, {
headers: {
'Content-Type': getMimeType(pathName),
},
});
} catch {
throw error(404, 'File not found.');
}
}
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
};
return mimeTypes[ext] || 'application/octet-stream';
}
the log output is usually something like it:
i've got the params { path: '/uploads_folder/cls/20241216-01/9Mb-report.html' }
here is my url file:///C:/projects/project_name/src/routes/[...path]/+server.js
here is the full path: C:projectsproject_name/static/uploads_folder/cls/20241216-01/9Mb-report.html
Hovewer when I deploy that code to CloudFoundry VM, my code encounters ‘404 / not found’ error and it seems like it never reaches this branch of code, as no log messages available in the logs.
my vite.config.ts is:
export default defineConfig({
plugins: [sveltekit()],
test: {
include: ['**/*.{test,spec}.{js,ts}']
},
define: {
'import.meta.env.VERSION': JSON.stringify(version),
'import.meta.env.WORKING_DIR': JSON.stringify(process.cwd()),
},
server: {
fs: {
strict: false,
},
}
});
My deployment manifest.yml is also nothing fancy:
---
applications:
- name: mywebsite
memory: 1G
instances: 1
routes:
- route: mywebsite.mycloudfoundry.com
stack: cflinuxfs4
buildpacks:
- https://github.com/cloudfoundry/nodejs-buildpack
services:
- serviceOne
- database
env:
PUBLIC_ENVOY_URL: "https://myenvoy.mycloudfoundry.com/"
BODY_SIZE_LIMIT: 25M
What blocks the route (or alters that) so the code is never reached and how to correct it?
1