英文:
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);
}
}
英文:
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);
}
}
答案1
得分: 5
这是一个简单的 Nuxt3 代码,它从 /public/test.txt
读取文件并从服务器 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
})
这是 StackBlitz 上运行的代码链接 CodeLink
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论