dart-lang/path

add "__filename" and "__dirname"

Closed this issue · 2 comments

I want to get the script path in a simpler way:

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

final String __filename = Platform.script.path.replaceFirst('/', '');
final String __dirname = path.dirname(__filename);

main(List<String> args) async {
  print('path.current: ${path.current}');
  print('__filename: $__filename');
  print('__dirname: $__dirname');
}

run:

ajanuw@ajanuw /d/ajanuw/dart-test
λ dart bin/main.dart
path.current: D:\ajanuw\dart-test
__filename: D:/ajanuw/dart-test/bin/main.dart
__dirname: D:/ajanuw/dart-test/bin

Platform.script.path is the Dart idiom for __filename from node. You can use normalize and dirname (as you have demonstrated here) to manipulate it.

It would not be possible for us to add a member named __filename since that would be private in Dart. We also don't want to add something that relies on Platform in this package since it would not be compatible with running on the web. I think the solution you'd pasted here is what I'd run with - though with perhaps avoiding a manual replaceFirst of the /...

Platform.script.toFilePath() is better.