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

问题描述 投票:4回答:3

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

我尝试写路径:

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

json reactjs meteor markdown
3个回答
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);

0
投票

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

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

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

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


0
投票

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

./private/data/发起.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配置文件

干杯

© www.soinside.com 2019 - 2024. All rights reserved.