How to read a file from an imported library

I have two packages, webserver

and utils

, which provides resources to the web server.

webserver

need access to static files inside utils. So I have this setup:

utils/
  lib/
    static.html

      

How can I access a file static.html

in one of my dart's scripts webserver

?

EDIT . What I've tried so far is using mirrors to get the library path and read from there. The problem with this approach is that if utils is included in package:

, the url

returned currentMirrorSystem().findLibrary(#utils).uri

is a uri package that cannot be converted to a real file object.

+3


source to share


2 answers


Use the Resource class, a new class in Dart SDK 1.12.

Usage example:

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

      



This works on VM since 1.12.

However, this does not directly address your need to get to the actual File object from the package: URI. Given the resource class today, you will need to route bytes from loadAsString()

to the HTTP server response object.

+4


source


I usually use Platform.script or mirrors to find the main folder of the top package (i.e. where pubspec.yaml is present) and find the exported asset packages imported. I agree that this is not a perfect solution, but it works

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);
}

      



Note that as of recently, Platform.script is not reliable in unit test when using a new test suite, so you can use the mirror tricks I suggest above and explained here: https://github.com/dart-lang/test / issues / 110

+1


source







All Articles