File, socket, HTTP, and other I/O support for non-web applications.
Important: Browser-based applications can't use this library. Only servers, command-line scripts, and Flutter mobile apps can import and use dart:io.
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:
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:
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.
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');
}
});
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 shelf 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.
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.
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:
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 connect()
method
and a URI that uses the Web Socket protocol.
The client can write to the WebSocket with the add()
method.
For example,
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.
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.
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();
startConnect
methods on client-side socket types S
,
ConnectionTask<S>
allows cancelling an attempt to connect to a host.
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.
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.
Process.kill
. [...]
RandomAccessFile
provides random access to the data in a
file. [...]
stdout
or stderr
. [...]
FileMode.append
gzip
const GZipCodec._default()
FileMode.read
const SystemEncoding()
const SystemEncoding()
FileMode.write
FileMode.writeOnly
FileMode.writeOnlyAppend
zlib
const ZLibCodec._default()
duration
. [...]