Reading static files in a library in Dart?
I am writing a library in Dart and I have static files in the library folder. I want to be able to read these files, but I'm not sure how to get the path to it ... not there __FILE__
or $0
like in some other languages.
Update: It seems that I was not clear enough. May this help you understand me:
test.dart
import 'foo.dart'; void main() { print(Foo.getMyPath()); }
foo.dart
library asd; class Foo { static Path getMyPath() => new Path('resources/'); }
This gives me the wrong folder location. This gives me a path to test.dart
+ resources/
, but I need a path to foo.dart
+ resources/
.
source to share
As mentioned, you can use mirrors. Here's an example using what you wanted to achieve:
test.dart
import 'foo.dart'; void main() { print(Foo.getMyPath()); }
foo.dart
library asd; import 'dart:mirrors'; class Foo { static Path getMyPath() => new Path('${currentMirrorSystem().libraries['asd'].url}/resources/'); }
It should output something like:
/ Users / Kai / test / Library / resources /
There will probably be a better way to do this in a future release. I'll update the answer when this is the case.
Update: . You can also define a private method in the library:
/** * Returns the path to the root of this library. */ _getRootPath() { var pathString = new Path(currentMirrorSystem().libraries['LIBNAME'].url).directoryPath.toString().replaceFirst('file:///', ''); return pathString; }
source to share
The dart mirror API (still experimental and not available on all platforms like dart2js yet) provides the url verb in LibraryMirror . This should give you what you want.
I don't know of any other way to get this information in the library.
#import('dart:mirrors'); #import('package:mylib/mylib.dart'); main(){ final urlOfLib = currentMirrorSystem().libraries['myLibraryName'].url; }
source to share
Usually the usual method to access resources that are in a static position with your library is using a relative path.
#import('dart:io'); ... var filePath = new Path('resources/cool.txt'); var file = new File.fromPath(filePath); // And if you really wanted, you can then get the full path // Note: below is for example only. It is missing various // integrity checks like error handling. file.fullPath.then((path_str) { print(path_str); });
See more API information on Path and File
Aside. If you absolutely wanted to get the same type of output as __FILE__
, you can do something like the following:
#import('dart:io'); ... var opts = new Options(); var path = new Path(opts.script); var file = new File.fromPath(path); file.fullPath().then((path_str) { print(path_str); });
source to share