I'd like to get the result of my command line 'pwd' from my Dart console program.
I wait for the process to start, install the listeners and wait for the task to complete.
I don't get the result though.
I guess that waiting for the first line makes the pwd to be executed BEFORE the listener could get a change to be installed. I my guess is true, how can I rewrite the code then?
var process = await Process.start('pwd', []);
process.stdout.listen((data) {
print('stdout: $data');
});
process.stderr.listen((data) {
print('stderr: $data');
});
int exitCode = await process.exitCode;
To print the current path it might be easier to use Process.run
. Awaiting this function you get an object of type ProcessResult
:
import 'dart:io';
void main() async {
final processResult = await Process.run('pwd', []);
print(processResult.stdout);
print('Exit code: ${processResult.exitCode}');
}
To make your original approach work, you would have to decode stdout
:
import 'dart:convert';
import 'dart:io';
void main(List<String> args) async {
final process = await Process.start('pwd', []);
process.stdout.transform(utf8.decoder).listen((data) {
print('Stdout: $data');
}).onDone(() async {
// Delay printing the exit code until after the stream has closed.
final exitCode = await process.exitCode;
print('Exit code: $exitCode');
});
}