2014-10-18 9 views
4

我正在編寫一個包,用於從lib目錄加載其他數據並希望提供一種簡單的方法來加載此類數據這樣的:如何通過`pub run`命令在腳本運行時找到包目錄的路徑

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

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

我做了兩個獨立的庫browser.dartstandalone.dart,類似於它是如何在Intl包完成。

從「瀏覽器」環境加載這些數據是相當容易的,但是對於「獨立」環境來說,由於使用pub run命令,並不容易。

當腳本運行簡單的$ dart myscript.dart時,我可以使用dart:io.PlatformPlatform.scriptPlatform.packageRoot屬性找到程序包路徑。

但是,當腳本與$ pub run tool/mytool運行,正確的方式來加載數據應該是:

  • 檢測腳本從酒吧運行命令
  • 運行找到酒館服務器主機
  • 從此服務器加載數據,因爲可能存在酒吧轉換器,我們無法直接從文件系統加載數據。

即使我想直接從文件系統,當該腳本與pub runPlatform.script回報/mytool路徑運行加載數據。

所以,問題是有什麼方法可以找到該腳本從pub run運行,以及如何找到pub服務器的服務器主機?

+0

「有沒有辦法找到該腳本是從酒吧跑跑步嗎?」。可能不會。 「如何找到pub服務器的服務器主機?」。如果沒有記錄某些行爲,只有在查看「pub」的源代碼後才能找到(臨時)解決方案。這種方法的可靠性非常低,但這一切都取決於您希望分配給代碼的可靠性級別。 – mezoni 2014-10-18 13:04:05

回答

4

我不確定這是否正確,但是當我使用pub run運行腳本時,Package.script實際上返回http://localhost:<port>/myscript.dart。所以,當方案爲http時,我可以使用http client下載,當它是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('...'); 
} 
+0

一個非常糟糕的生活案例('pub run')的一個很好的解決方案。我不知道這件事。現在我永遠不會使用它們('pub run')。 – mezoni 2014-10-18 12:55:10

相關問題