I need to find out the directory in which the Dart script (which is currently running) is located. How do I go about doing this?
Previously, this was possible through new Options().script
, but that class is no more. The arguments list from main(args)
doesn't help, since it only contains arguments, not the executed Dart file (at least on Mac OS X).
According to BREAKING CHANGE: dart:io Platform and Options are deprecated, and will be removed and Breaking Change: Platform.script is a Uri, dart:platform library is gone new Options().script
should be replaced by Platform.script
.
Note that Platform.script
returns an Uri and you should consider using toFilePath to get the file path from the file URI.
As noted the simple method is:
import 'dart:io';
print(Platform().script);
> file:///home/..../dcli_unit_tester/bin/dcli_unit_tester.dart
This is a file url, so to get the actual path use:
import 'dart:io';
print(Platform().script.toFilePath());
Of course you wanted the directory rather than the script so:
import 'dart:io';
import 'package:path/path.dart';
final pathToScript = Platform().script.toFilePath();
final pathToDirectory = dirname(pathToScript);
print(pathToDirectory);
> /home/..../dcli_unit_tester/bin
There are a few things you should understand when attempting to get the directory of the script in that the directory will change depending on how you run the script.
In particular if running your script from a globally activated package then you might not (should not) want to use the script's dirirectory for storing things.
Here is the output from Platform if you run it from the cli:
dart bin/dcli_unit_tester.dart -p
executable: dart
script: file:///home/..../dcli_unit_tester/bin/dcli_unit_tester.dart
Now if you run the same script from a globally activated package:
pub global activate dcli_unit_tester
dcli_unit_tester -p
executable: dart
script: file:///home/..../.pub-cache/global_packages/dcli_unit_tester/bin/dcli_unit_tester.dart-2.14.2.snapshot
In this case the directory is in pub-cache which by nature is transitory, so don't store anything that you want to get back later.
Now if you compile the script:
dart compile exe bin/dcli_unit_tester.dart
bin/dcli_unit_tester.exe -p
executable: bin/dcli_unit_tester.exe
script: file:///home/..../dcli_unit_tester/bin/dcli_unit_tester.exe
If you run the same test from a unit test the script will be the test.dll file not you script. I will update this answer once I work out how to get the script directory when running under unit tests (if it is even possible).
If you are building a console app you can use the dcli package:
import 'package:dcli/dcli.dart'
print(DartScript.self.pathToScript);
print(DartScript.self.pathToScriptDirectory);
> /home/..../dcli_unit_tester/bin/dcli_unit_tester.dart
> /home/..../dcli_unit_tester/bin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With