Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read txt file in nuxt 3 in a folder

I am attempting to read a file data.txt in my nuxt 3 app in folder src/resources/data.txt. When the application is built it is attempting to read it in .output/src/resources/data.txt

Is it possible to read a file in nuxt 3? Where can I put the file for nuxt to find it?

Here is my function:


    async function readData(fname: string):Promise<String | undefined>{
      const { __dirname } = useGlobalFileParams()
      try {
        const data = await fs.promises.readFile(path.resolve(__dirname,fname), 'utf-8')                           
         return data
      } catch (err) {
        console.log(err);
      }
   }

like image 906
BreenDeen Avatar asked Sep 17 '25 12:09

BreenDeen


1 Answers

Here is a simple Nuxt3 code that read the file from /public/test.txt and return it from server api.

// /server/api/read.get.ts

import * as path from 'node:path'
import * as fs from 'node:fs'

export default defineEventHandler(async (event) => {
  const filePath = path.join(process.cwd(), 'public', 'test.txt')
  const data = await fs.promises.readFile(filePath, 'utf-8')
  return data
})

Here is a StackBlitz Link of the running code CodeLink

like image 81
nur_riyad Avatar answered Sep 19 '25 08:09

nur_riyad