How to find the path to the package directory when the script works with the `pub run` command

I am writing a package that downloads additional data from a directory liband would like to provide an easy way to load this data like this:

const dataPath = 'mypackage/data/data.json';

initializeMyLibrary(dataPath).then((_) {
  // library is ready
});

I created two separate libraries browser.dartand standalone.dart, similarly to how it is done in the Intl package .

Downloading this data from a “browser” environment is pretty easy, but when it comes to a “standalone” environment, it’s not so easy because of the command pub run.

When the script works with a simple one $ dart myscript.dart, I can find the package path using dart: io.Platform Platform.script and Platform.packageRoot.

But when the script works with $ pub run tool/mytool, the correct way to load data should be:

  • , script pub
  • - pub
  • , pub, .

, script pub run, Platform.script /mytool .

, , , script pub run pub?

+4
1

, , script pub run, Package.script http://localhost:<port>/myscript.dart. , http, http-, file, .

- :

import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as ospath;

Future<List<int>> loadAsBytes(String path) {
  final script = Platform.script;
  final scheme = Platform.script.scheme;

  if (scheme.startsWith('http')) {
    return new HttpClient().getUrl(
        new Uri(
            scheme: script.scheme,
            host: script.host,
            port: script.port,
            path: 'packages/' + path)).then((req) {
      return req.close();
    }).then((response) {
      return response.fold(
          new BytesBuilder(),
          (b, d) => b..add(d)).then((builder) {
        return builder.takeBytes();
      });
    });

  } else if (scheme == 'file') {
    return new File(
        ospath.join(ospath.dirname(script.path), 'packages', path)).readAsBytes();
  }

  throw new Exception('...');
}
+4

All Articles