While the file does exist in the current directory, the `readFileSync` function is unable to locate

For my latest SvelteKit project, I was developing a Joke API using Bun as the runtime and TypeScript as the programming language. The goal of this API was to fetch one random dad joke from a text file that contained 363 jokes. Everything was going smoothly until I encountered a problem - the file reader couldn't locate the file. Even though I provided the correct file path ./jokes.txt, the reader kept throwing errors. I initially suspected that Bun's integration might be causing the issue due to its newness, so I attempted to use readFileSync instead, but that didn't resolve the problem either.

Here is the snippet of 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");

  // More code here...

  return {
    joke: joke
  }
}

Below is an overview of 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

Answer №1

readFileSync may behave unpredictably because it relies on the relative path of code execution rather than the current file location. To avoid this, it is recommended to always compare the code file's location with the runtime execution and resolve it like so:

const path = require("path");

fs.readFileSync(path.resolve(__dirname, "./jokes.txt"), "utf-8")

Answer №2

If you encounter an ENOENT error when using readFileSync, it simply means that the file does not exist. This is often caused by mistakenly providing a path that does not lead to the intended location.

The relative path ./jokes.txt does not necessarily correspond to the directory where your current file is located; instead, it refers to the process's current working directory. It's essential to check this using process.cwd() to understand the actual working directory.

To determine where the relative path resolves to, you can use path.resolve('./jokes.txt'), which will likely reveal that there is no jokes.txt at that location.

If you indeed want to read a file from the same directory as your current file, consider utilizing __dirname:

readFileSync(path.join(__dirname, "jokes.txt"), "utf-8"); 

In addition, here are some unrelated remarks:

  • Using readFileSync within an async context contradicts the purpose of asynchronous operations since it blocks execution. Consider using the async fs promises API instead.

  • Regarding the db variable, while executing queries like:

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

    be cautious about using string templates in SQL queries as they could make your code vulnerable to SQL injections. It's recommended to use parameterized queries for security purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JavaScript code to jQuery and integrating it into a WordPress website has become a common practice

I recently developed a working javascript function as shown below: function calc(A,B,SUM) { var one = Number(A); var two = Number(document.getElementById(B).value); if (isNaN(one)) { alert('Invalid entry: '+A); one=0; } if (isNaN(tw ...

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...

Enhance filtering capabilities in ng-repeat by adding controls

After utilizing ng-repeat to display some JSON data, I have incorporated form controls to filter output data from another JSON file. Here is a simplified example: First JSON data: var technologies = [ {"id":"5", "slug":"mysql", "label":"MyS ...

What strategies can I use to address the issue of requiring a type before it has been defined?

Encountered an intriguing challenge. Here are the types I'm working with: export interface QuestionPrimative { question : string; id : string; name : string; formctrl? : string; formgrp? : string; lowEx ...

An error was encountered: SyntaxError - An unexpected token '!' was found

I am having trouble creating a react cluster map. I encountered a SyntaxError, and I'm not sure what went wrong. Initially, my map was working fine, but after using the use-supercluster npm package, it started showing an Uncaught SyntaxError: Unexpect ...

"Angularjs tip: If the value of the href attribute is null, make sure

I am attempting to add a condition to either href or ng-href. The condition I want to apply is if email !== null. My current code appears as follows: <a ng-attr-href="{{email !== null}}" href="mailto:{{email | lowercase}}">{{email | lowercase | nu ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

Classic ASP offers a feature that allows users to select all checkboxes at once

I'm looking to create a functionality where there is a 'Select all' checkbox along with individual checkboxes for each database record. Is it possible to use JavaScript to ensure that when the 'Select all' checkbox is checked, all ...

Using Javascript to Change the Radio Station Station

I am a beginner in the world of programming and I am attempting to make this feature work. My goal is to give the user the ability to select the radio station they want to listen to. Here is what I have come up with, but unfortunately it is not functioni ...

Recaptcha Request exceeded time limit within the bootstrap modal dialogue box

I am encountering an issue with the reCaptcha on my website. The first one, located on a regular page, is functioning properly. However, the second one is placed within a modal popup that appears after clicking a button. Upon inspecting the browser consol ...

What is preventing me from running UNIT Tests in VSCode when I have both 2 windows and 2 different projects open simultaneously?

I have taken on a new project that involves working with existing unit tests. While I recently completed a course on Angular testing, I am still struggling to make the tests run smoothly. To aid in my task, I created a project filled with basic examples f ...

Issues arise with tabbed content as default content fails to display and classes are not added upon clicking

I'm currently working on a tabbed module that consists of three tabs. Here's how it operates: When the user clicks on a carousel_element, it reveals carousel_hidden-text within that div and displays it in another div called carousel_quote. I&ap ...

Utilizing React-Router-Redux alongside the powerful features of React-Bootstrap

I've been struggling with this issue for some time now! My goal is to create a 'main app container' that consistently displays the logo, navigation... I plan on using react-bootstrap to enhance its appearance. Currently, I'm encounter ...

Ensure the Image URL is valid before modifying the State in React/Next

This code snippet is written in React/Next.js with styled-components. Hey there, I have a component that displays a blog banner using a background-image. The URL for the image comes from a state variable that currently holds a default image path. const [b ...

Discover the secret to automatically calling a function every minute when the page is loaded!

Our team is currently developing a PhoneGap application with 4 pages. We are in need of posting the current latitude and longitude every minute to our server. Fortunately, we are familiar with how to post values to the server as well as how to retrieve the ...

Add a CSS class to an innerHTML element just a single time

I currently have 2 files available: data.php page.php The data.php file is responsible for fetching a row from a SQL database and sending it to the page.php file. Within the page.php file, there is a JavaScript script that receives this row through AJAX ...

The coverflow of Swiper is not displaying properly within a Div container

Just to clarify, I am not very experienced and do not know many best practices. I am learning as I go along with projects. I am using Swiper for a game list slider, but when I place it inside another Div, it disappears completely. I can position and size ...

Puppeteer cannot fully render SVG charts

When using this code in Try Puppeteer: const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen'); const linkHandlers = await pa ...

The process of passing the ID value to another function is malfunctioning in JavaScript

Currently working on a sudoku puzzle as part of a toy project. My goal is to retrieve the ID value of blank spaces and pass it to another function. However, I am facing an issue where the numbers are not getting inserted into the blanks upon clicking. Can ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...