Skip to content

dart:io

File, socket, HTTP, and other I/O support for non-web applications.

Important: Browser-based apps can't use this library. Only the following can import and use the dart:io library:

  • Servers
  • Command-line scripts
  • Flutter mobile apps
  • Flutter desktop apps

This library allows you to work with files, directories, sockets, processes, HTTP servers and clients, and more. Many operations related to input and output are asynchronous and are handled using Futures or Streams, both of which are defined in the dart:async library.

To use the dart:io library in your code:

dart
import 'dart:io';

For an introduction to I/O in Dart, see the dart:io library tour.

An instance of File, Directory, or Link represents a file, directory, or link, respectively, in the native file system.

You can manipulate the file system through objects of these types. For example, you can rename a file or directory:

dart
File myFile = File('myFile.txt');
myFile.rename('yourFile.txt').then((_) => print('file renamed'));

Many methods provided by the File, Directory, and Link classes run asynchronously and return a Future.

FileSystemEntity

File, Directory, and Link all extend FileSystemEntity. In addition to being the superclass for these classes, FileSystemEntity has a number of static methods for working with paths.

To get information about a path, you can use the FileSystemEntity static methods such as FileSystemEntity.isDirectory, FileSystemEntity.isFile, and FileSystemEntity.exists. Because file system access involves I/O, these methods are asynchronous and return a Future.

dart
FileSystemEntity.isDirectory(myPath).then((isDir) {
  if (isDir) {
    print('$myPath is a directory');
  } else {
    print('$myPath is not a directory');
  }
});

HttpServer and HttpClient

The classes HttpClient and HttpServer provide low-level HTTP functionality.

Instead of using these classes directly, consider using more developer-friendly and composable APIs found in packages.

For HTTP clients, look at package:http.

For HTTP servers, look at Write HTTP servers on dart.dev.

Process

The Process class provides a way to run a process on the native machine. For example, the following code spawns a process that recursively lists the files under web.

dart
Process.start('ls', ['-R', 'web']).then((process) {
  stdout.addStream(process.stdout);
  stderr.addStream(process.stderr);
  process.exitCode.then(print);
});

Using Process.start returns a Future, which completes with a Process object when the process has started. This Process object allows you to interact with the process while it is running. Using Process.run returns a Future, which completes with a ProcessResult object when the spawned process has terminated. This ProcessResult object collects the output and exit code from the process.

When using Process.start, you need to read all data coming on the Process.stdout and Process.stderr streams, otherwise the system resources will not be freed.

WebSocket

The WebSocket class provides support for the web socket protocol. This allows full-duplex communications between client and server applications.

A web socket server uses a normal HTTP server for accepting web socket connections. The initial handshake is a HTTP request which is then upgraded to a web socket connection. The server upgrades the request using WebSocketTransformer and listens for the data on the returned web socket. For example, here's a mini server that listens for 'ws' data on a WebSocket:

dart
runZoned(() async {
  var server = await HttpServer.bind('127.0.0.1', 4040);
  server.listen((HttpRequest req) async {
    if (req.uri.path == '/ws') {
      var socket = await WebSocketTransformer.upgrade(req);
      socket.listen(handleMsg);
    }
  });
}, onError: (e) => print("An error occurred."));

The client connects to the WebSocket using the WebSocket.connect method and a URI that uses the Web Socket protocol. The client can write to the WebSocket with the WebSocket.add method. For example,

dart
var socket = await WebSocket.connect('ws://127.0.0.1:4040/ws');
socket.add('Hello, World!');

Check out the websocket_sample app, which uses WebSockets to communicate with a server.

Socket and ServerSocket

Clients and servers use Sockets to communicate using the TCP protocol. Use ServerSocket on the server side and Socket on the client. The server creates a listening socket using the bind() method and then listens for incoming connections on the socket. For example:

dart
ServerSocket.bind('127.0.0.1', 4041)
  .then((serverSocket) {
    serverSocket.listen((socket) {
      socket.transform(utf8.decoder).listen(print);
    });
  });

A client connects a Socket using the connect() method, which returns a Future. Using write(), writeln(), or writeAll() are the easiest ways to send data over the socket. For example:

dart
Socket.connect('127.0.0.1', 4041).then((socket) {
  socket.write('Hello, World!');
});

Besides Socket and ServerSocket, the RawSocket and RawServerSocket classes are available for lower-level access to async socket IO.

Standard output, error, and input streams

This library provides the standard output, error, and input streams, named stdout, stderr, and stdin, respectively.

The stdout and stderr streams are both IOSinks and have the same set of methods and properties.

To write a string to stdout:

dart
stdout.writeln('Hello, World!');

To write a list of objects to stderr:

dart
stderr.writeAll([ 'That ', 'is ', 'an ', 'error.', '\n']);

The standard input stream is a true Stream, so it inherits properties and methods from the Stream class.

To read text synchronously from the command line (the program blocks waiting for user to type information):

dart
String? inputText = stdin.readLineSync();

Classes

ClassDescription
BytesBuilderBuilds a list of bytes, allowing bytes and lists of bytes to be added at the end.
CompressionOptionsOptions controlling compression in a WebSocket.
ConnectionTask<S>A cancelable connection attempt.
ContentTypeA MIME/IANA media type used as the value of the HttpHeaders.contentTypeHeader header.
CookieRepresentation of a cookie. For cookies received by the server as Cookie header values only name and value properties will be set. When building a cookie for the 'set-cookie' header in the server and when receiving cookies in the client as 'set-cookie' headers all fields can be used.
DatagramA data packet received by a RawDatagramSocket.
DirectoryA reference to a directory (or folder) on the file system.
FileA reference to a file on the file system.
FileLockType of lock when requesting a lock on a file.
FileModeThe modes in which a File can be opened.
FileStatThe result of calling the POSIX stat() function on a file system object.
FileSystemCreateEventFile system event for newly created file system objects.
FileSystemDeleteEventFile system event for deletion of file system objects.
FileSystemEntityThe common superclass of File, Directory, and Link.
FileSystemEntityTypeThe type of an entity on the file system, such as a file, directory, or link.
FileSystemEventBase event class emitted by FileSystemEntity.watch.
FileSystemModifyEventFile system event for modifications of file system objects.
FileSystemMoveEventFile system event for moving of file system objects.
GZipCodecThe GZipCodec encodes raw bytes to GZip compressed bytes and decodes GZip compressed bytes to raw bytes.
HeaderValueRepresentation of a header value in the form:
HttpClientAn HTTP client for communicating with an HTTP server.
HttpClientBasicCredentialsRepresents credentials for basic authentication.
HttpClientBearerCredentialsRepresents credentials for bearer token authentication.
HttpClientCredentialsRepresents credentials for authentication in HttpClient.
HttpClientDigestCredentialsRepresents credentials for digest authentication.
HttpClientRequestHTTP request for a client connection.
HttpClientResponseHTTP response for a client connection.
HttpConnectionInfoInformation about an HttpRequest, HttpResponse, HttpClientRequest, or HttpClientResponse connection.
HttpConnectionsInfoSummary statistics about an HttpServers current socket connections.
HttpDateUtility functions for working with dates with HTTP specific date formats.
HttpHeadersHeaders for HTTP requests and responses.
HttpOverridesThis class facilitates overriding HttpClient with a mock implementation. It should be extended by another class in client code with overrides that construct a mock implementation. The implementation in this base class defaults to the actual HttpClient implementation. For example:
HttpRequestA server-side object that contains the content of and information about an HTTP request.
HttpResponseAn HTTP response, which returns the headers and data from the server to the client in response to an HTTP request.
HttpServerA server that delivers content, such as web pages, using the HTTP protocol.
HttpSessionThe HttpRequest.session of an HttpRequest.
HttpStatusHTTP status codes. Exported in dart:io and dart:html.
InternetAddressAn internet address or a Unix domain address.
InternetAddressTypeThe type, or address family, of an InternetAddress.
IOOverridesFacilities for overriding various APIs of dart:io with mock implementations.
IOSinkA combined byte and text output.
LinkReferences to filesystem links.
NetworkInterfaceA NetworkInterface represents an active network interface on the current system. It contains a list of InternetAddresses that are bound to the interface.
PipeAn anonymous pipe that can be used to send data in a single direction i.e. data written to write can be read using read.
PlatformInformation about the environment in which the current program is running.
ProcessThe means to execute a program.
ProcessInfoMethods for retrieving information about the current process.
ProcessResultThe result of running a non-interactive process started with Process.run or Process.runSync.
ProcessSignalOn Posix systems, ProcessSignal is used to send a specific signal to a child process, see Process.kill.
ProcessStartModeModes for running a new process.
RandomAccessFileRandom access to the data in a file.
RawDatagramSocketAn unbuffered interface to a UDP socket.
RawSecureServerSocketA server socket providing a stream of low-level RawSecureSockets.
RawSecureSocketRawSecureSocket provides a secure (SSL or TLS) network connection.
RawServerSocketA listening socket.
RawSocketA TCP connection.
RawSocketEventEvents for the RawDatagramSocket, RawSecureSocket, and RawSocket.
RawSocketOptionThe RawSocketOption is used as a parameter to Socket.setRawOption and RawSocket.setRawOption to customize the behaviour of the underlying socket.
RawSynchronousSocketA low-level class for communicating synchronously over a TCP socket.
RawZLibFilterThe RawZLibFilter class provides a low-level interface to zlib.
ReadPipeThe "read" end of an Pipe created by Pipe.create.
RedirectInfoRedirect information.
ResourceHandleA wrapper around OS resource handle so it can be passed via Socket as part of SocketMessage.
SameSiteCookie cross-site availability configuration.
SecureServerSocketA server socket, providing a stream of high-level Sockets.
SecureSocketA TCP socket using TLS and SSL.
SecurityContextThe object containing the certificates to trust when making a secure client connection, and the certificate chain and private key to serve from a secure server.
ServerSocketA listening socket.
SocketA TCP connection between two sockets.
SocketControlMessageControl message part of the SocketMessage received by a call to RawSocket.readMessage.
SocketDirectionThe SocketDirection is used as a parameter to Socket.close and RawSocket.close to close a socket in the specified direction(s).
SocketMessageA socket message received by a RawDatagramSocket.
SocketOptionAn option for a socket which is configured using Socket.setOption.
StdinThe standard input stream of the process.
StdioTypeThe type of object a standard IO stream can be attached to.
StdoutAn IOSink connected to either the standard out or error of the process.
SystemEncodingThe system encoding is the current code page on Windows and UTF-8 on Linux and Mac.
TlsProtocolVersionA Transport Layer Security (TLS) version.
WebSocketA two-way HTTP communication object for client or server applications.
WebSocketStatusWebSocket status codes used when closing a WebSocket connection.
WebSocketTransformerThe WebSocketTransformer provides the ability to upgrade a HttpRequest to a WebSocket connection. It supports both upgrading a single HttpRequest and upgrading a stream of HttpRequests.
WritePipeThe "write" end of an Pipe created by Pipe.create.
X509CertificateX509Certificate represents an SSL certificate, with accessors to get the fields of the certificate.
ZLibCodecThe ZLibCodec encodes raw bytes to ZLib compressed bytes and decodes ZLib compressed bytes to raw bytes.
ZLibDecoderThe ZLibDecoder is used by ZLibCodec and GZipCodec to decompress data.
ZLibEncoderThe ZLibEncoder encoder is used by ZLibCodec and GZipCodec to compress data.
ZLibOptionExposes ZLib options for input parameters.

Exceptions

ExceptionDescription
CertificateExceptionAn exception that happens in the handshake phase of establishing a secure network connection, when looking up or verifying a certificate.
FileSystemExceptionException thrown when a file operation fails.
HandshakeExceptionAn exception that happens in the handshake phase of establishing a secure network connection.
HttpException
IOExceptionBase class for all IO related exceptions.
OSErrorAn Exception holding information about an error from the operating system.
PathAccessExceptionException thrown when a file operation fails because the necessary access rights are not available.
PathExistsExceptionException thrown when a file operation fails because the target path already exists.
PathNotFoundExceptionException thrown when a file operation fails because a file or directory does not exist.
ProcessException
RedirectException
SignalException
SocketExceptionException thrown when a socket operation fails.
StdinExceptionException thrown by some operations of Stdin
StdoutExceptionException thrown by some operations of Stdout
TlsExceptionA secure networking exception caused by a failure in the TLS/SSL protocol.
WebSocketException

Enums

EnumDescription
HttpClientResponseCompressionStateEnum that specifies the compression state of the byte stream of an HttpClientResponse.

Functions

FunctionDescription
exitExit the Dart VM process immediately with the given exit code.
sleepSleep for the duration specified in duration.
stdioTypeWhether a stream is attached to a file, pipe, terminal, or something else.

Properties

PropertyDescription
exitCodeGet the global exit code for the Dart VM.
pidReturns the PID of the current process.
stderrThe standard output stream of errors written by this program.
stdinThe standard input stream of data read by this program.
stdoutThe standard output stream of data written by this program.

Constants

ConstantDescription
gzipAn instance of the default implementation of the GZipCodec.
systemEncodingThe current system encoding.
zlibAn instance of the default implementation of the ZLibCodec.

Typedefs

TypedefDescription
BadCertificateCallback