An introduction to the dart:io library

Written by Mads AgerMarch 2012 (updated September 2018)

The dart:io libraryis aimed at code that runs in Flutter and the standalone Dart VM.In this article we will give you a feel forwhat is currently possible with dart:ioby going through a couple of examples.

Note: When writing a Flutter app, use Flutter-specific APIs instead of dart:io whenever possible. For example, use the Flutter asset support to load images and other assets into your app.

Dart is a single-threaded programming language.If an operation blocks the Dart thread,the application makes no progress before that operation completes.For scalability it is therefore crucial that no I/O operations block.Instead of blocking on I/O operations,dart:io uses an asynchronous programming model inspired bynode.js,EventMachine, andTwisted.

The Dart VM and the event loop

Before we dive into asynchronous I/O operations,it might be useful to explain how the standalone Dart VM operates.

When executing a server-side application,the Dart VM runs in an event loop withan associated event queue of pending asynchronous operations.The VM terminates when it has executed the current code to completionand no more pending operations are in the queue.

One simple way to add an event to the event queue is toschedule a function to be called in the future.You can do this by creating aTimer object.The following example registers a timer with the event queueand then drops off the end of main().Because a pending operation is in the event queue,the VM does not terminate at that point.After one second,the timer fires and the code in the argument callback executes.Once that code executes to completion,no more pending operations are in the event queueand the VM terminates.

  1. import 'dart:async';
  2.  
  3. void main() {
  4. Timer(Duration(seconds: 1), () => print('timer'));
  5. print('end of main');
  6. }

Running this example at the command line, we get:

  1. $ dart timer.dart
  2. end of main
  3. timer

Had we made the timer repeating by using theTimer.periodic constructor,the VM would not terminateand would continue to print out ‘timer’ every second.

File system access

The dart:io library provides access to files and directories through theFile andDirectory classes.

The following example prints its own source code.To determine the location of the source code being executed,we use thePlatformclass.

  1. import 'dart:convert';
  2. import 'dart:io';
  3.  
  4. Future<void> main() async {
  5. var file = File(Platform.script.toFilePath());
  6. print("${await (file.readAsString(encoding: ascii))}");
  7. }

Notice that the readAsString() method is asynchronous;it returns a Futurethat returns the contents of the fileonce the file has been read from the underlying system.This asynchronicity allows the Dart thread to perform other workwhile waiting for the I/O operation to complete.

To illustrate more detailed file operations,let’s change the example to read the contentsonly up to the first semicolon and then to print that.You could do this in two ways:either open the file for random access,or open aStreamfor the file and stream in the data.

Here is a version that opens the file for random access operations.The code opens the file for reading and then reads one byte at a timeuntil it encounters the char code for ;.

  1. import 'dart:io';
  2.  
  3. Future<void> main() async {
  4. final semicolon = ';'.codeUnitAt(0);
  5. var result = <int>[];
  6.  
  7. final script = File(Platform.script.toFilePath());
  8. RandomAccessFile file = await script.open(mode: FileMode.read);
  9.  
  10. // Deal with each byte.
  11. while (true) {
  12. final byte = await file.readByte();
  13. result.add(byte);
  14. if (byte == semicolon) {
  15. print(String.fromCharCodes(result));
  16. await file.close();
  17. break;
  18. }
  19. }
  20. }

When you see a use of async or await, you are seeing a Future in action.Both the open() and readByte() methods return a Future object.

This code is, of course,a very simple use of random-access operations.Operations are available for writing,seeking to a given position, truncating, and so on.

Let’s implement a version using a stream.The following code opens the file for reading presenting the contentas a stream of lists of bytes. Like all streams in Dart you listen onthis stream (using await for) and the data is given in chunks.

  1. import 'dart:io';
  2.  
  3. Future<void> main() async {
  4. var result = <int>[];
  5.  
  6. Stream<List<int>> stream = File(Platform.script.toFilePath()).openRead();
  7. final semicolon = ';'.codeUnitAt(0);
  8.  
  9. await for (var data in stream) {
  10. for (int i = 0; i < data.length; i++) {
  11. result.add(data[i]);
  12. if (data[i] == semicolon) {
  13. print(String.fromCharCodes(result));
  14. return;
  15. }
  16. }
  17. }
  18. }

The stream subscription is implicitly handled by await for.Exiting the await for statement — using break, return, or an uncaught exception —cancels the subscription.

Stream<List<int>> is used in multiple places in dart:io:when working with stdin, files, sockets, HTTP connections, and so on.Similarly, IOSink objectsare used to stream data tostdout, files, sockets, HTTP connections, and so on.

Interacting with processes

For the simple case, useProcess.run()to run a processand collect its output. Use run() when you don’tneed interactive control over the process.

  1. import 'dart:io';
  2.  
  3. Future<void> main() async {
  4. // List all files in the current directory,
  5. // in UNIX-like operating systems.
  6. ProcessResult results = await Process.run('ls', ['-l']);
  7. print(results.stdout);
  8. }

You can also start a process by creating aProcess objectusingProcess.start().

Once you have a Process object you can interact with the processby writing data to its stdin sink,reading data from its stderr and stdout streams,and killing the process.When the process exits, the exitCode future completes withthe exit code of the process.

The following example runs ls -l in a separate processand prints the output and the exit code for the process to stdout.Since we are interested in getting lines,we use aUtf8Decoder(which decodes chunks of bytes into strings) followed by aLineSplitter(which splits the strings at line boundaries).

  1. import 'dart:convert';
  2. import 'dart:io';
  3.  
  4. Future<void> main() async {
  5. final process = await Process.start('ls', ['-l']);
  6. var lineStream =
  7. process.stdout.transform(Utf8Decoder()).transform(LineSplitter());
  8. await for (var line in lineStream) {
  9. print(line);
  10. }
  11.  
  12. await process.stderr.drain();
  13. print('exit code: ${await process.exitCode}');
  14. }

Notice that exitCode can complete before all of the lines of outputhave been processed. Also notethat we do not explicitly close the process. In order tonot leak resources we have to listen to both the stderr and stdoutstreams. We use await for to listen to stdout,and stderr.drain() to listen to (and discard) stderr.

Instead of printing the output to stdout,we can use the streaming classesto pipe the output of the process to a file.

  1. import 'dart:io';
  2.  
  3. Future<void> main() async {
  4. final output = File('output.txt').openWrite();
  5. Process process = await Process.start('ls', ['-l']);
  6.  
  7. // Wait for the process to finish; get the exit code.
  8. final exitCode = (await Future.wait([
  9. process.stdout.pipe(output), // Send stdout to file.
  10. process.stderr.drain(), // Discard stderr.
  11. process.exitCode
  12. ]))[2];
  13.  
  14. print('exit code: $exitCode');
  15. }

Writing web servers

dart:io makes it easy to write HTTP servers and clients.To write a simple web server,all you have to do is create anHttpServerand hook up a listener (using await for) to its stream of HttpRequests.

Here is a simple web serverthat just answers ‘Hello, world’ to any request.

  1. import 'dart:io';
  2.  
  3. Future<void> main() async {
  4. final server = await HttpServer.bind('127.0.0.1', 8082);
  5. await for (HttpRequest request in server) {
  6. request.response.write('Hello, world');
  7. await request.response.close();
  8. }
  9. }

Running this applicationand pointing your browser to ‘http://127.0.0.1:8082’gives you ‘Hello, world’ as expected.

Let’s add a bit more and actually serve files.The base path for every file that we serve will bethe location of the script.If no path is specified in a request we will serve index.html.For a request with a path,we will attempt to find the file and serve it.If the file is not found we will respond with a ‘404 Not Found’ status.We make use of the streaming interfaceto pipe all the data read from a file directly to the response stream.

  1. import 'dart:io';
  2.  
  3. Future<void> runServer(String basePath) async {
  4. final server = await HttpServer.bind('127.0.0.1', 8082);
  5. await for (HttpRequest request in server) {
  6. await handleRequest(basePath, request);
  7. }
  8. }
  9.  
  10. Future<void> handleRequest(String basePath, HttpRequest request) async {
  11. final String path = request.uri.toFilePath();
  12. // PENDING: Do more security checks here.
  13. final String resultPath = path == '/' ? '/index.html' : path;
  14. final File file = File('$basePath$resultPath');
  15. if (await file.exists()) {
  16. try {
  17. await request.response.addStream(file.openRead());
  18. } catch (exception) {
  19. print('Error happened: $exception');
  20. await sendInternalError(request.response);
  21. }
  22. } else {
  23. await sendNotFound(request.response);
  24. }
  25. }
  26.  
  27. Future<void> sendInternalError(HttpResponse response) async {
  28. response.statusCode = HttpStatus.internalServerError;
  29. await response.close();
  30. }
  31.  
  32. Future<void> sendNotFound(HttpResponse response) async {
  33. response.statusCode = HttpStatus.notFound;
  34. await response.close();
  35. }
  36.  
  37. Future<void> main() async {
  38. // Compute base path for the request based on the location of the
  39. // script, and then start the server.
  40. final script = File(Platform.script.toFilePath());
  41. await runServer(script.parent.path);
  42. }

Writing HTTP clients is very similar to using theHttpClientclass.

Feature requests welcome

The dart:io library is already capable of performing a lot of tasks.For example, the pub.dev site uses dart:io.

Please give dart:io a spin and let us know what you think.Feature requests are very welcome!When you file a bug or feature request,use dartbug.com.To find reported issues, search for thelibrary-io label.