You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit+Bun项目中readFileSync无法找到已存在的本地文件

问题描述

我基于SvelteKit框架,用Bun作为运行时、TypeScript开发笑话API,需要从包含363条冷笑话的jokes.txt文件中随机读取一行内容。目前其他功能正常,但文件读取模块始终找不到目标文件。我尝试过Bun.file和fs.readFileSync两种方式,路径都写的./jokes.txt,文件确实存在于routes/api目录下,但就是读取失败。

代码片段
import { readFileSync } from "fs";

import { db } from "$lib/db";
import { sql } from "drizzle-orm";
import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core';

export async function GET() {
  let file = readFileSync("./jokes.txt", "utf-8");

  const jokes = file.split("\n");

  const today = new Date();

  const jokecords = sqliteTable("jokecords", {
    id: integer("id").primaryKey(),
    joke: text("joke"),
    month: text("month"),
    day: text("day")
  });

  const matches = await db.select().from(jokecords).where(
    sql`month = ${today.getMonth().toString()} and day = ${today.getDay().toString()}`
  );

  let joke;

  if (matches.length > 0) {
    joke = matches[0];
  }
  else {
    joke = jokes[Math.floor(Math.random() * jokes.length)];
    await db.insert(jokecords).values({
      joke: joke,
      month: today.getMonth().toString(),
      day: today.getDay().toString()
    });
  }

  return {
    joke: joke
  }
}
项目文件结构
.sveltekit
node_modules
src
  lib
    db.ts
  routes
    api
      +server.ts
      jokes.txt
      jokes-backup.txt
    +layout.svelte
    +page.svelte
  app.d.ts
  app.html
  app.pcss
static
.gitignore
.npmrc
bun.lockb
package.json
postcss.config.cjs
README.md
svelte.config.js
tailwind.config.cjs
tsconfig.json
vite.config.ts
解决方案

问题核心是相对路径解析错误:在SvelteKit的服务器端路由(+server.ts)中,./指向的是项目根目录,而非当前文件所在的routes/api目录,导致找不到jokes.txt。

提供两种可行的解决方式:

方式一:使用绝对路径(适配fs模块)

借助Node.js的path模块拼接绝对路径,确保精准定位文件:

import { readFileSync } from "fs";
import { join } from "path";

// 拼接当前模块目录与jokes.txt的路径
const filePath = join(import.meta.dirname, "./jokes.txt");
let file = readFileSync(filePath, "utf-8");

import.meta.dirname会返回当前+server.ts文件所在的目录路径,再拼接jokes.txt即可指向正确位置。

方式二:使用Bun原生文件读取API(推荐)

既然用了Bun作为运行时,直接用其原生API配合绝对路径更简洁:

import { join } from "path";

const filePath = join(import.meta.dirname, "./jokes.txt");
const fileContent = await Bun.file(filePath).text();
const jokes = fileContent.split("\n");

另外注意:原代码中file.split(" ")是换行符的写法错误,需改为file.split("\n"),否则无法正确分割每行笑话。

内容的提问来源于stack exchange,提问作者Nathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:50:19