如何从导入的库中读取文件

How to read file from an imported library

我有两个包:webserverutils,它们为网络服务器提供资产。

webserver 需要访问 utils 中的静态文件。所以我有这个设置:

utils/
  lib/
    static.html

如何在 webserver 中的一个飞镖脚本中访问 static.html 文件?

编辑:到目前为止我尝试的是使用镜像获取库的路径,并从那里读取它。这种方法的问题是,如果 utils 包含在 package: 中,currentMirrorSystem().findLibrary(#utils).uri 返回的 url 是一个包 uri,无法转换为实际文件实体。

我倾向于使用 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

使用资源 class,Dart SDK 1.12 中的新 class。

用法示例:

var resource = new Resource('package:myapp/myfile.txt');
var contents = await resource.loadAsString();
print(contents);

从 1.12 开始,这适用于 VM。

但是,这并没有直接解决您从包:URI 获取实际文件实体的需要。鉴于今天的资源 class,您必须将字节从 loadAsString() 路由到 HTTP 服务器的响应对象。