Issue
I was working on a Joke API for my SvelteKit project with Bun as the runtime and TypeScript as the programming language. My Joke API involves getting one random line from a text file containing 363 dad jokes. For that I obviously had to read the file. So I implemented that method and it worked splendidly...except for one part. The file reader couldn't find the file. The file location I put in was ./jokes.txt
, which was exactly where it was. However, the file reader said that it just can't find it. I thought that because I was using Bun.file
to read the file that it was causing issues because Bun is relatively new, so I tried readFileSync
and that didn't work either.
Here's my code:
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
}
}
and this is my file structure
.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
Solution
readFileSync
can runs in an unespecified way because it depends on the relative path of the execution of code, not your current file. The best way to avoid this is to always compare the location of the code file with the execution runtime and resolve it, like:
const path = require("path");
fs.readFileSync(path.resolve(__dirname, "./jokes.txt"), "utf-8")
Answered By - Rafael Fernandes
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.