dart-lang / io

Utilities for the Dart VM's dart:io.
https://pub.dev/packages/io
BSD 3-Clause "New" or "Revised" License
49 stars 15 forks source link

String was not appended to the end of the file on append mode. #90

Open kawa-yo opened 1 year ago

kawa-yo commented 1 year ago

I was trying to log to a file using logging. Here's the code.

logger.onRecord.listen((event) {
  file.writeAsString(event.message + "\n", mode: FileMode.append);
});

Resulting file was just one line, a message logger somewhere listened.

When I replaced writeAsString with writeAsStringSync, things went well and all messages were logged to the file.

Is this an expected behavior?

Minimized code

import 'dart:io';

void main() {
  var file1 = File("async.txt");
  for (int i = 0; i < 10; i++) {
    file1.writeAsString("$i times\n", mode: FileMode.append);
  }

  var file2 = File("sync.txt");
  for (int i = 0; i < 10; i++) {
    file2.writeAsStringSync("$i times\n", mode: FileMode.append);
  }
}

async.txt

7 times

sync.txt

0 times
1 times
2 times
3 times
4 times
5 times
6 times
7 times
8 times
9 times
ArbazShaikh077 commented 1 year ago

@kawa-yo Since all the file operations are asynchronous you must use either below syntax: await file1.writeAsString("$i times\n", mode: FileMode.append); or file2.writeAsStringSync("$i times\n", mode: FileMode.append); Your async.txt will not get the expected result until you use the await keyword before the method call.