我有两个软件包:webserver
和utils
,它们为网络服务器提供资源。
webserver
需要访问utils中的静态文件。所以我有这个设置:
utils/
lib/
static.html
如何在static.html
的某个dart脚本中访问webserver
文件?
编辑:到目前为止,我尝试使用镜像来获取库的路径,并从那里读取它。这种方法的问题是,如果package:
中包含utils,url
返回的currentMirrorSystem().findLibrary(#utils).uri
是一个包uri,无法转换为实际的文件实体
答案 0 :(得分:4)
使用Resource类,Dart SDK 1.12中的新类。
用法示例:
var resource = new Resource('package:myapp/myfile.txt');
var contents = await resource.loadAsString();
print(contents);
这适用于VM,自1.12开始。
但是,这并不能直接解决从包:URI到达实际File实体的需要。鉴于今天的Resource类,您必须将loadAsString()
中的字节路由到HTTP服务器的Response对象。
答案 1 :(得分:1)
我倾向于使用Platform.script或镜像来查找主包顶级文件夹(即pubspec.yaml所在的位置)并查找导入的包导出资产。我同意这不是一个完美的解决方案,但它有效
import 'dart:io';
import 'package:path/path.dart';
String getProjectTopPath(String resolverPath) {
String dirPath = normalize(absolute(resolverPath));
while (true) {
// Find the project root path
if (new File(join(dirPath, "pubspec.yaml")).existsSync()) {
return dirPath;
}
String newDirPath = dirname(dirPath);
if (newDirPath == dirPath) {
throw new Exception("No project found for path '$resolverPath");
}
dirPath = newDirPath;
}
}
String getPackagesPath(String resolverPath) {
return join(getProjectTopPath(resolverPath), 'packages');
}
class _TestUtils {}
main(List<String> arguments) {
// User Platform.script - does not work in unit test
String currentScriptPath = Platform.script.toFilePath();
String packagesPath = getPackagesPath(currentScriptPath);
// Get your file using the package name and its relative path from the lib folder
String filePath = join(packagesPath, "utils", "static.html");
print(filePath);
// use mirror to find this file path
String thisFilePath = (reflectClass(_TestUtils).owner as LibraryMirror).uri.toString();
packagesPath = getPackagesPath(thisFilePath);
filePath = join(packagesPath, "utils", "static.html");
print(filePath);
}
要注意的是,由于最近在使用新测试包时Platform.script在单元测试中不可靠,因此您可以使用我在上面提出并在此处解释的镜像技巧:https://github.com/dart-lang/test/issues/110