TanStackT
TanStack6mo ago
10 replies
sacred-emerald

Reading file in server function

The following code works in development but when I build the application the file being read is not found. The contents of the src/data directory are not copied into the build. What's the correct way to read a file with a server function? And where should the file be placed?

import { createServerFn } from '@tanstack/react-start';
import { readFile } from 'node:fs/promises';
import { join } from 'path';
import matter from 'gray-matter';
import { MarkdownMetadata } from '@/model/blog/markdown-metadata';

export const getAboutMarkdownServerFn = createServerFn({
    method: 'GET',
}).handler(async ({ data }) => {
    try {
        const md = await readFile(`src/data/md/about.md`, 'utf-8');
        const { data: mdData, content } = matter(md);
        return {
            ...(mdData as MarkdownMetadata),
            content: content.trimStart(),
        };
    } catch (err: any) {
        if (err.code === 'ENOENT') {
            // File not found
            console.warn(`Markdown file not found for About page`);
            return null; // Or throw a custom error, or return an empty object fallback
        }
        // Unexpected error
        throw err;
    }
});`
Was this page helpful?