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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With