如何设置项目中文件的路径?

How to set the path to the file in the project?

如果保留完整路径,则一切正常。但这行不通,因为在其他计算机上应该是 运行。

我尝试写路径:

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 的东西。

您可以使用节点中的 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);

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

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

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

如果您仍然决定从文件系统访问文件,您可以在 Meteor.settings 中指定一个位置,这意味着您可以为每个 server/computer 独立设置它 运行上。

您可以放置​​您的文件,例如在应用程序源的 "private" 目录中,例如

./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' }));

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

的 ENV 配置文件

干杯