node.js - 无法读取函数文件夹中的文件

标签 node.js firebase express

我有一个在 Firebase 上运行的 expressjs 应用程序,从我的 firebase-express/functions/index.js 我正在尝试读取位于 functions/api/swagger/swagger 的文件.yaml.

const swaggerDocument = YAML.load('./api/swagger/swagger.yaml');

当我在本地运行 firebase serve 时,出现以下错误。

Error: ENOENT: no such file or directory, open 'C:\Users\Tulio\Desktop\firebase-express\api\swagger\swagger.yaml'
    at Error (native)
    at Object.fs.openSync (fs.js:642:18)
    at Object.fs.readFileSync (fs.js:510:33)
    at Function.Utils.getStringFromFile (C:\Users\Tulio\Desktop\firebase-express\functions\node_modules\yamljs\lib\Utils.js:284:19)
    at Function.Yaml.parseFile (C:\Users\Tulio\Desktop\firebase-express\functions\node_modules\yamljs\lib\Yaml.js:46:21)
    at Function.Yaml.load (C:\Users\Tulio\Desktop\firebase-express\functions\node_modules\yamljs\lib\Yaml.js:78:17)
    at Object.<anonymous> (C:\Users\Tulio\Desktop\firebase-express\functions\index.js:11:30)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)

它正在寻找位于 'C:\Users\Tulio\Desktop\firebase-express\api\swagger\swagger.yaml' 的文件,因此解决方案必须是将我的参数更改为是否包括文件夹“功能”?

const swaggerDocument = YAML.load('./functions/api/swagger/swagger.yaml');

现在我得到另一个错误,它将路径显示为:

no such file or directory, open 'C:\Users\Tulio\Desktop\firebase-express\functions\functions\api\swagger\swagger.yaml'

注意到'functions\functions'了吗?出于某种原因,当我将“functions/”添加到路径时,它会附加另一个“functions/”,从而使路径无效。

如何获取 functions 文件夹中文件的正确路径?

最佳答案

使用路径

var path = require('path');
var swagger_path =  path.resolve(__dirname,'./api/swagger/swagger.yaml');
console.log(swagger_path);

这将在任何环境中获取正确的路径。

关于node.js - 无法读取函数文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105334/

相关文章:

mysql - NodeJS MySQL 异步调用阻止进程退出

Flutterfire 配置 - 未处理的异常且没有 firebase 初始化

javascript - 使用 JavaScript 从 Firebase 下载为 JSON

linux - node.js ftdi 模块抛出错误 : libftd2xx. 所以:无法打开共享对象文件

json - 执行 "npm install"后安装了太多 npm 模块

javascript - mongodb中另一个模型中的数组中仅保存objectID

javascript - 使用 Angular 设置 Express

node.js - 发送后表达响应正文

node.js - Sequelize 关联方法不起作用

ios - Firebase Remote Config 推送多长时间?