【问题标题】:How to find path to the package directory when the script is running with `pub run` command使用`pub run`命令运行脚本时如何找到包目录的路径
【发布时间】:2014-12-13 17:43:59
【问题描述】:

我正在编写一个从lib 目录加载其他数据的包,并希望提供一种简单的方法来加载这些数据,如下所示:

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

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

我创建了两个独立的库browser.dartstandalone.dart,类似于Intl 包中的做法。

从“浏览器”环境中加载这些数据很容易,但在“独立”环境中,由于pub run 命令,就不是那么容易了。

当脚本使用简单的$ dart myscript.dart 运行时,我可以使用dart:io.Platform Platform.scriptPlatform.packageRoot 属性找到包路径。

但是当脚本以$ pub run tool/mytool运行时,加载数据的正确方式应该是:

  • 通过 pub run 命令检测脚本正在运行
  • 找到发布服务器主机
  • 从此服务器加载数据,因为可能存在 pub 转换器,我们无法直接从文件系统加载数据。

即使我想直接从文件系统加载数据,当脚本以pub run 运行时,Platform.script 也会返回/mytool 路径。

那么,问题是有什么方法可以找到脚本是从pub run 运行的,以及如何找到 pub 服务器的服务器主机?

【问题讨论】:

  • “有什么方法可以发现脚本是从 pub run 运行的吗?”。可能不是。 “如何找到 pub 服务器的服务器主机?”。如果某些行为未记录在案,则只有在查看“pub”的源代码后才能找到(临时)解决方案。这种方法的可靠性非常低,但这完全取决于您希望分配给代码的可靠性级别。

标签: dart command-line-interface dart-pub dart-io


【解决方案1】:

我不确定这是不是正确的方法,但是当我使用pub run 运行脚本时,Package.script 实际上返回http://localhost:<port>/myscript.dart。所以,当scheme为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('...');
}

【讨论】:

  • 一个非常糟糕的生活案例的好解决方案 (pub run)。我不知道。现在我再也不会使用它们了 (pub run)。
猜你喜欢
  • 2021-07-17
  • 2014-03-18
  • 1970-01-01
  • 2017-12-07
  • 2010-09-12
  • 2011-06-11
  • 2016-05-08
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多