dart:io library

File, socket, HTTP, and other I/O support for server applications.

File, socket, HTTP, and other I/O support for server applications.

The I/O library is used for Dart server applications, which run on a stand-alone Dart VM from the command line. This library does not work in browser-based applications.

This library allows you to work with files, directories, sockets, processes, HTTP servers and clients, and more.

To use this library in your code:

import 'dart:io';

Note: 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.

File, Directory, and Link

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:

File myFile = new 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 'isDirectory', 'isFile', and 'exists'. Because file system access involves I/O, these methods are asynchronous and return a Future.

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

HttpServer and HttpClient

The classes HttpServer and HttpClient provide HTTP server and HTTP client functionality.

The HttpServer class provides the basic functionality for implementing an HTTP server. For some higher-level building-blocks, we recommend that you try the http_server pub package, which contains a set of high-level classes that, together with the HttpServer class in this library, make it easier to implement HTTP servers.

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.

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

Using 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 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 start(), you need to read all data coming on the stdout and 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. Use the WebSocket class in the dart:html library for web clients.

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:

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

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

WebSocket.connect('ws://127.0.0.1:4040/ws').then((socket) {
  socket.add('Hello, World!');
});

Check out the dartiverse_search sample for a client/server pair that uses WebSockets to communicate.

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:

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:

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':

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

To write a list of objects to 'stderr':

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):

 String inputText = stdin.readLineSync();

Other resources

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

To learn more about I/O in Dart, refer to the tutorial about writing command-line apps.

Classes

BytesBuilder
Builds a list of bytes, allowing bytes and lists of bytes to be added at the end.
IOException
Base class for all IO related exceptions.
OSError
An OSError object holds information about an error from the operating system.
ZLibOption
Exposes ZLib options for input parameters.
ZLibCodec
The ZLibCodec encodes raw bytes to ZLib compressed bytes and decodes ZLib compressed bytes to raw bytes.
GZipCodec
The GZipCodec encodes raw bytes to GZip compressed bytes and decodes GZip compressed bytes to raw bytes.
ZLibEncoder
The ZLibEncoder encoder is used by ZLibCodec and GZipCodec to compress data.
ZLibDecoder
The ZLibDecoder is used by ZLibCodec and GZipCodec to decompress data.
Directory
A reference to a directory (or folder) on the file system.
FileMode
The modes in which a File can be opened.
File
A reference to a file on the file system.
RandomAccessFile
RandomAccessFile provides random access to the data in a file.
FileSystemException
Exception thrown when a file operation fails.
FileSystemEntityType
The type of an entity on the file system, such as a file, directory, or link.
FileStat
A FileStat object represents the result of calling the POSIX stat() function on a file system object. It is an immutable object, representing the snapshotted values returned by the stat() call.
FileSystemEntity
The common super class for File, Directory, and Link objects.
FileSystemEvent
Base event class emitted by FileSystemEntity.watch.
FileSystemCreateEvent
File system event for newly created file system objects.
FileSystemModifyEvent
File system event for modifications of file system objects.
FileSystemDeleteEvent
File system event for deletion of file system objects.
FileSystemMoveEvent
File system event for moving of file system objects.
HttpStatus
HTTP status codes.
HttpServer
A server that delivers content, such as web pages, using the HTTP protocol.
HttpConnectionsInfo
Summary statistics about an HttpServers current socket connections.
HttpHeaders
Headers for HTTP requests and responses.
HeaderValue
Representation of a header value in the form:
HttpSession
ContentType
Representation of a content type. An instance of ContentType is immutable.
Representation of a cookie. For cookies received by the server as Cookie header values only name and value fields 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.
HttpRequest
A server-side object that contains the content of and information about an HTTP request.
HttpResponse
An HTTP response, which returns the headers and data from the server to the client in response to an HTTP request.
HttpClient
A client that receives content, such as web pages, from a server using the HTTP protocol.
HttpClientRequest
HTTP request for a client connection.
HttpClientResponse
HTTP response for a client connection.
HttpClientCredentials
HttpClientBasicCredentials
Represents credentials for basic authentication.
HttpClientDigestCredentials
Represents credentials for digest authentication. Digest authentication is only supported for servers using the MD5 algorithm and quality of protection (qop) of either "none" or "auth".
HttpConnectionInfo
Information about an HttpRequest, HttpResponse, HttpClientRequest, or HttpClientResponse connection.
RedirectInfo
Redirect information.
DetachedSocket
When detaching a socket from either the HttpServer or the HttpClient due to a HTTP connection upgrade there might be unparsed data already read from the socket. This unparsed data together with the detached socket is returned in an instance of this class.
HttpException
RedirectException
HttpDate
Utility functions for working with dates with HTTP specific date formats.
IOSink
Helper class to wrap a StreamConsumer> and provide utility functions for writing to the StreamConsumer directly. The IOSink buffers the input given by all StringSink methods and will delay an addStream until the buffer is flushed.
Link objects are references to filesystem links.
Platform
Information about the environment in which the current program is running.
Process
The means to execute a program.
ProcessResult
ProcessResult represents the result of running a non-interactive process started with Process.run or Process.runSync.
ProcessSignal
On Posix systems, ProcessSignal is used to send a specific signal to a child process, see Process.kill.
SignalException
ProcessException
InternetAddressType
InternetAddressType is the type an InternetAddress. Currently, IP version 4 (IPv4) and IP version 6 (IPv6) are supported.
InternetAddress
An internet address.
NetworkInterface
A NetworkInterface represent an active network interface on the current system. It contains a list of InternetAddresss, that's bound to the interface.
RawServerSocket
A RawServerSocket represents a listening socket, and provides a stream of low-level RawSocket objects, one for each connection made to the listening socket.
RawServerSocketReference
A RawServerSocketReference.
ServerSocket
A ServerSocket represents a listening socket, and provides a stream of Socket objects, one for each connection made to the listening socket.
ServerSocketReference
A ServerSocketReference.
SocketDirection
The SocketDirection is used as a parameter to Socket.close and RawSocket.close to close a socket in the specified direction(s).
SocketOption
The SocketOption is used as a parameter to Socket.setOption and RawSocket.setOption to set customize the behaviour of the underlying socket.
RawSocketEvent
Events for the RawSocket.
RawSocket
The RawSocket is a low-level interface to a socket, exposing the raw events signaled by the system. It's a Stream of RawSocketEvents.
Socket
A high-level class for communicating over a TCP socket.
Datagram
Datagram package. Data send to and received from datagram sockets contains the internet address and port of the destination or source togeter with the data.
RawDatagramSocket
The RawDatagramSocket is a low-level interface to an UDP socket, exposing the raw events signaled by the system. It's a Stream of RawSocketEvents.
SocketException
Stdin
Stdin allows both synchronous and asynchronous reads from the standard input stream.
Stdout
Stdout represents the IOSink for either stdout or stderr.
StdoutException
StdioType
The type of object a standard IO stream is attached to.
SystemEncoding
The system encoding is the current code page on Windows and UTF-8 on Linux and Mac.
SecureSocket
A high-level class for communicating securely over a TCP socket, using TLS and SSL. The SecureSocket exposes both a Stream and an IOSink interface, making it ideal for using together with other Streams.
RawSecureSocket
RawSecureSocket provides a secure (SSL or TLS) network connection. Client connections to a server are provided by calling RawSecureSocket.connect. A secure server, created with RawSecureServerSocket, also returns RawSecureSocket objects representing the server end of a secure connection. The certificate provided by the server is checked using the certificate database provided in SecureSocket.initialize, and/or the default built-in root certificates.
X509Certificate
X509Certificate represents an SSL certificate, with accessors to get the fields of the certificate.
TlsException
A secure networking exception caused by a failure in the TLS/SSL protocol.
HandshakeException
An exception that happens in the handshake phase of establishing a secure network connection.
CertificateException
An exception that happens in the handshake phase of establishing a secure network connection, when looking up or verifying a certificate.
SecureServerSocket
The SecureServerSocket is a server socket, providing a stream of high-level Sockets.
RawSecureServerSocket
The RawSecureServerSocket is a server socket, providing a stream of low-level RawSecureSockets.
WebSocketStatus
WebSocket status codes used when closing a WebSocket connection.
WebSocketTransformer
The 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.
WebSocket
A two-way HTTP communication object for client or server applications.
WebSocketException

Enums

ProcessStartMode
Modes for running a new process.
FileLock
Type of lock when requesting a lock on a file.

Properties

exitCode int
read / write
pid int
read-only
stdin Stdin
read-only
stdout Stdout
read-only
stderr Stdout
read-only

Constants

ZLIB = const ZLibCodec._default()
An instance of the default implementation of the ZLibCodec.
GZIP = const GZipCodec._default()
An instance of the default implementation of the GZipCodec.
READ = FileMode.READ
The mode for opening a file only for reading.
WRITE = FileMode.WRITE
The mode for opening a file for reading and writing. The file is overwritten if it already exists. The file is created if it does not already exist.
APPEND = FileMode.APPEND
The mode for opening a file for reading and writing to the end of it. The file is created if it does not already exist.
WRITE_ONLY = FileMode.WRITE_ONLY
Mode for opening a file for writing only. The file is overwritten if it already exists. The file is created if it does not already exist.
WRITE_ONLY_APPEND = FileMode.WRITE_ONLY_APPEND
Mode for opening a file for writing only to the end of it. The file is created if it does not already exist.
SYSTEM_ENCODING = const SystemEncoding()
The current system encoding.

Functions

exit(int code) → void
Exit the Dart VM process immediately with the given exit code.
sleep(Duration duration) → void
Sleep for the duration specified in duration.
stdioType(object) → StdioType
For a stream, returns whether it is attached to a file, pipe, terminal, or something else.

Exceptions / Errors

IOException
Base class for all IO related exceptions.
FileSystemException
Exception thrown when a file operation fails.
HttpException
RedirectException
SignalException
ProcessException
SocketException
StdoutException
TlsException
A secure networking exception caused by a failure in the TLS/SSL protocol.
HandshakeException
An exception that happens in the handshake phase of establishing a secure network connection.
CertificateException
An exception that happens in the handshake phase of establishing a secure network connection, when looking up or verifying a certificate.
WebSocketException