【问题标题】:Read file with firebase function使用 firebase 功能读取文件
【发布时间】:2021-01-09 19:57:12
【问题描述】:

我有一个 Firebase 函数,想读取一个 html 文件,存储在一个子文件夹中。

── functions
    ├── src
    |   ├── index.ts // Here is the function
    |   ├── html
    |   |   ├── template.html // the file I want to read

我尝试通过const html = fs.readFileSync('./html/template.html'); 读取文件,但它总是告诉我

错误:ENOENT:没有这样的文件或目录,打开 './html/template.html' 在 Object.openSync

我几乎解决了有关此主题的 stackoverflow 上的所有问题,但对我没有任何帮助。我也尝试将文件放在与函数相同的文件夹中,但它总是给我错误。

我是否需要安装一些包或以某种方式导入文件才能访问它?

【问题讨论】:

    标签: typescript firebase file google-cloud-functions


    【解决方案1】:

    对于任何从搜索结果进入此帖子的人...

    解决这个问题的方法不是使用path.resolve

    这里的问题是,fs.readFileSync 解析相对于process.cwd() 的路径(目录节点是从那里执行的)。对于 firebase 函数,这将始终是为 firebase.json 中的 source 定义的目录(默认情况下,functions 目录)。
    此处记录了此功能:
    https://nodejs.org/api/path.html#path_path_resolve_paths

    如果在处理完所有给定的路径段后,还没有生成绝对路径,则使用当前工作目录。

    path.resolve 具有相同的行为。它总是解析为绝对路径。如果您传入的路径不是绝对路径,则会在其前面添加 process.cwd()
    Node 文档中似乎没有记录,但您可以在此处亲自查看:https://github.com/nodejs/node/blob/029d1fd797975ef89b867f9d606257f0f070a462/lib/path.js#L1017

    您可以通过两种方式解决此问题:

    • 使用相对于函数根目录的路径(在本例中为src/html/template.html
    • 使用__dirname (path.resolve(__dirname, './html/template.html')

    __dirname 是一个变量,它总是返回当前正在执行的文件所在目录的绝对路径。

    【讨论】:

      【解决方案2】:

      您需要使用path.resolve() 方法,它将您的路径解析为绝对路径,然后再将其传递给fs.readdirSync() 方法。所以以下应该可以解决问题:

          const path = require('path');
      
          // ...
      
          let content = fs.readFileSync(
              path.resolve('./html/template.html')
          );
      

      【讨论】:

      • 谢谢,这成功了!我还必须将路径稍微更改为“src/html/template.html”,现在它可以工作了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 2013-06-26
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      相关资源
      最近更新 更多