如何使用Meteor
列出文件夹中的所有文件。我在我的应用上安装了FS
个集合并cfs:filesystem
。我在文档中找不到它。
答案 0 :(得分:2)
另一种方法是添加shelljs npm模块。
要添加npm模块,请参阅:https://github.com/meteorhacks/npm
然后你只需要做一些事情:
var shell = Meteor.npmRequire('shelljs');
var list = shell.ls('/yourfolder');
Shelljs文档: https://github.com/arturadib/shelljs
答案 1 :(得分:1)
简短的回答是FS.Collection创建一个可以像其他任何一样对待的Mongo集合,即,您可以使用find()
列出条目。
答案很长......
使用cfs:filesystem,您可以创建一个镜像服务器上给定文件夹的mongo数据库,如下所示:
// in lib/files.js
files = new FS.Collection("my_files", {
stores: [new FS.Store.FileSystem("my_files", {"~/test"})] // creates a ~/test folder at the home directory of your server and will put files there on insert
});
然后,您可以在客户端上访问此集合,以将文件上载到服务器的~test /目录:
files.insert(new File(['Test file contents'], 'my_test_file'));
然后你可以列出服务器上的文件,如下所示:
files.find(); // returns [ { createdByTransform: true,
_id: 't6NoXZZdx6hmJDEQh',
original:
{ name: 'my_test_file',
updatedAt: (Date)
size: (N),
type: '' },
uploadedAt: (Date),
copies: { my_files: [Object] },
collectionName: 'my_files'
}
copies
对象似乎包含所创建文件的实际名称,例如
files.findOne().copies
{
"my_files" : {
"name" : "testy1",
"type" : "",
"size" : 6,
"key" : "my_files-t6NoXZZdx6hmJDEQh-my_test_file", // This is the name of the file on the server at ~/test/
"updatedAt" : ISODate("2015-03-29T16:53:33Z"),
"createdAt" : ISODate("2015-03-29T16:53:33Z")
}
}
这种方法的问题在于它只跟踪通过Collection进行的更改;如果手动将某些内容添加到〜/ test目录中,它将不会镜像到Collection中。例如,如果在服务器上我运行类似......
mkfile 1k ~/test/my_files-aaaaaaaaaa-manually-created
然后我在集合中寻找它,它不会在那里:
files.findOne({"original.name": {$regex: ".*manually.*"}}) // returns undefined
如果您只想在服务器上直接列出文件,可以考虑只运行ls
。从https://gentlenode.com/journal/meteor-14-execute-a-unix-command/33开始,您可以使用节点child_process.exec()
执行任意UNIX命令。您可以使用process.env.PWD
(来自this question)访问应用根目录。因此,最后如果要列出公共目录中的所有文件,可以执行以下操作:
exec = Npm.require('child_process').exec;
console.log("This is the root dir:");
console.log(process.env.PWD); // running from localhost returns: /Users/me/meteor_apps/test
child = exec('ls -la ' + process.env.PWD + '/public', function(error, stdout, stderr) {
// Fill in this callback with whatever you actually want to do with the information
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null) {
console.log('exec error: ' + error);
}
});
这必须在服务器上运行,因此如果您想要客户端上的信息,则必须将其放在方法中。这也是非常不安全的,取决于你如何构建它,所以你想要考虑如何阻止人们列出你服务器上的所有文件和文件夹,或者更糟糕的是 - 运行任意高管。
您选择哪种方法可能取决于您真正想要实现的目标。