【问题标题】:How to set the path to the file in the project?如何设置项目中文件的路径?
【发布时间】:2019-04-28 20:40:16
【问题描述】:

如果您保留完整路径,那么一切正常。但这不起作用,因为它应该在其他计算机上运行。

我尝试写路径:

const jsonData = JSON.parse(fs.readFileSync('/app/data/faqQuestions', { encoding: 'utf8' }));

控制台中的问题:

Error: ENOENT: no such file or directory, open 'C:\app\data\faqQuestions.json'

如果之前去掉斜线:app/data/faqQuestions.json:

Error: ENOENT: no such file or directory, open 'C:\Users\mi\AppData\Local\Temp\meteor-test-runqxi9h2.08bd.meteor\local\build\programs\server\app\data\faqQuestions.json'

必须规定在任何计算机上工作的正确路径。 我需要 PWD 之类的东西。

【问题讨论】:

  • /app/data/ 是您的 Meteor 项目中的相对路径还是在您的项目之外?

标签: json reactjs meteor markdown


【解决方案1】:

您可以使用节点中的path 模块来获取文件系统中的正确路径:

const path = require('path');
const fs = require('fs');

const filepath = path.resolve('/app/data');
const jsonFile = fs.readFileSync(path.join(filepath, 'faqQuestions.json'), { encoding: 'utf8' });
const jsonData = JSON.parse(jsonFile);
console.log('data', jsonData);

【讨论】:

  • 感谢您的选择,但它给出了错误 Error: ENOENT: no such file or directory, open 'C:\app\data\faqQuestions.json'
【解决方案2】:

欢迎来到 Stack Overflow。您不应该像这样直接访问文件系统。有几个原因:

1) 位置因计算机而异 2) 在生产环境中部署到 docker 容器时,本地文件系统是只读的,除非您专门为此目的挂载卷 3)当 Meteor 构建时,它运行的包在 .meteor/local... 的某个地方,所以你不能真正使用 pwd

将文件存储在外部存储中(如 S3 存储桶,请参阅 ostrio:files 了解如何执行此操作)或将它们作为对象放入 Mongo 数据库中更有意义。

如果您仍然确定要从文件系统访问文件,您可以在 Meteor.settings 中指定一个位置,这意味着您可以为正在运行的每台服务器/计算机独立设置它。

【讨论】:

    【解决方案3】:

    您可以放置​​您的文件,例如在应用程序源的“私有”目录中,例如

    ./private/data/faq.json

    要获取您可以使用的内容:

    // use for file access
    var fs = Npm.require('fs');
    
    // using this meteor lib, gives secure access to folder structure
    var files = Npm.require("./mini-files");
    
    // save reference to serverDir
    var serverDir = files.pathResolve(__meteor_bootstrap__.serverDir);
    
    // Taken from meteor/tools/bundler.js#L1509
    // currently the directory structure has not changed for build
    var assetBundlePath = files.pathJoin(serverDir, 'assets', 'app');
    
    // location of the private data folder
    var dataPath = files.pathJoin(assetBundlePath, 'data');
    

    之后应该可以在服务器上加载你的 json

    const jsonData = JSON.parse(fs.readFileSync(files.pathJoin(dataPath, 'faqQuestions'), { encoding: 'utf8' }));
    

    我在一个流星组件中使用它来处理位于 Github (https://github.com/4commerce-technologies-AG/meteor-package-env-settings) 的 ENV 配置文件

    干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      相关资源
      最近更新 更多