如何在Nuxt 3中读取文件夹中的txt文件。

huangapple go评论89阅读模式
英文:

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&lt;String | undefined&gt;{
      const { __dirname } = useGlobalFileParams()
      try {
        const data = await fs.promises.readFile(path.resolve(__dirname,fname), &#39;utf-8&#39;)                           
         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 &#39;node:path&#39;
import * as fs from &#39;node:fs&#39;

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

Here is a StackBlitz Link of the running code CodeLink

huangapple
  • 本文由 发表于 2023年6月12日 08:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定