The IO 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.
Global exit code for the Dart VM.
The exit code is global for the Dart VM and the last assignment to exitCode from any isolate determines the exit code of the Dart VM on normal termination.
Returns the PID if the current process.
Exit the Dart VM process immediately with the given status code.
This does not wait for any asynchronous operations to terminate. Using exit is therefore very likely to lose data.
Sleep for the duration specified in duration.
Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.
Representation of a content type. An instance of ContentType is immutable.
Gets the character set.
Gets the mime-type, without any parameters.
Gets the primary type.
Gets the sub type.
Creates a new content type object setting the primary type and sub type. The charset and additional parameters can also be set using charset and parameters. If charset is passed and parameters contains charset as well the passed charset will override the value in parameters. Keys and values passed in parameters will be converted to lower case.
Creates a new content type object from parsing a Content-Type header value. As primary type, sub type and parameter names and values are not case sensitive all these values will be converted to lower case. Parsing this string
text/html; charset=utf-8will create a content type object with primary type
text
, sub type html
and parameter charset
with value utf-8
.
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.
Gets and sets the domain.
Gets and sets the expiry date.
Gets and sets whether this cookie is HTTP only.
Gets and sets the max age. A value of 0
means delete cookie now.
Gets and sets the name.
Gets and sets the path.
Gets and sets whether this cookie is secure.
Gets and sets the value.
Creates a new cookie optionally setting the name and value.
Creates a new cookie by parsing a header value from a 'set-cookie' header.
Returns the formatted string representation of the cookie. The string representation can be used for for setting the Cookie or 'set-cookie' headers
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.
Directory objects are used for working with directories.
Gets the path of this directory.
Creates a directory object pointing to the current working directory.
Sets the current working directory of the Dart process including all running isolates. The new value set can be either a Directory or a String.
The new value is passed to the OS's system call unchanged, so a relative path passed as the new working directory will be resolved by the OS.
Note that setting the current working directory is a synchronous operation and that it changes the the working directory of all isolates.
Use this with care - especially when working with asynchronous operations and multiple isolates. Changing the working directory, while asynchronous operations are pending or when other isolates are working with the file system, can lead to unexpected results.
Creates a directory object. The path is either an absolute path, or it is a relative path which is interpreted relative to the directory in which the Dart VM was started.
Creates a directory object from a Path object. The path is either an absolute path, or it is a relative path which is interpreted relative to the directory in which the Dart VM was started.
Creates the directory with this name.
If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists nothing is done.
Returns a Future<Directory>
that completes with this directory once it has been created. If the directory cannot be created the future completes with an exception.
Synchronously creates the directory with this name.
If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists nothing is done.
If the directory cannot be created an exception is thrown.
Creates a temporary directory with a name based on the current path. The path is used as a template, and additional characters are appended to it to make a unique temporary directory name. If the path is the empty string, a default system temp directory and name are used for the template.
Returns a Future<Directory>
that completes with the newly created temporary directory.
Synchronously creates a temporary directory with a name based on the current path. The path is used as a template, and additional characters are appended to it to make a unique temporary directory name. If the path is the empty string, a default system temp directory and name are used for the template. Returns the newly created temporary directory.
Deletes this directory.
If recursive is false, the directory must be empty. Only directories and links to directories will be deleted.
If recursive is true, this directory and all sub-directories and files in the directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target.
If recursive is true, the target is deleted even if it is a file, or a link to a file, not only if it is a directory. This behavior allows delete to be used to unconditionally delete any file system object.
Returns a Future<Directory>
that completes with this directory when the deletion is done. If the directory cannot be deleted, the future completes with an exception.
Synchronously deletes this directory.
If recursive is false, the directory must be empty.
If recursive is true, this directory and all sub-directories and files in the directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target.
If recursive is true, the target is deleted even if it is a file, or a link to a file, not only if it is a directory. This behavior allows delete to be used to unconditionally delete any file system object.
Throws an exception if the directory cannot be deleted.
Lists the sub-directories and files of this Directory. Optionally recurses into sub-directories.
If followLinks is false, then any symbolic links found are reported as Link objects, rather than as directories or files, and are not recursed into.
If followLinks is true, then working links are reported as directories or files, depending on their type, and links to directories are recursed into. Broken links are reported as Link objects. If a symbolic link makes a loop in the file system, then a recursive listing will not follow a link twice in the same recursive descent, but will report it as a Link the second time it is seen.
The result is a stream of FileSystemEntity objects for the directories, files, and links.
Lists the sub-directories and files of this Directory. Optionally recurses into sub-directories.
If followLinks is false, then any symbolic links found are reported as Link objects, rather than as directories or files, and are not recursed into.
If followLinks is true, then working links are reported as directories or files, depending on their type, and links to directories are recursed into. Broken links are reported as Link objects. If a link makes a loop in the file system, then a recursive listing will not follow a link twice in the same recursive descent, but will report it as a Link the second time it is seen.
Returns a List containing FileSystemEntity objects for the directories, files, and links.
Renames this directory. Returns a Future<Directory>
that completes with a Directory instance for the renamed directory.
If newPath identifies an existing directory, that directory is replaced. If newPath identifies an existing file, the operation fails and the future completes with an exception.
Synchronously renames this directory. Returns a Directory instance for the renamed directory.
If newPath identifies an existing directory, that directory is replaced. If newPath identifies an existing file the operation fails and an exception is thrown.
Returns a human readable string for this Directory instance.
Returns a string representation of this object.
String encodings.
SYSTEM encoding is the current code page on Windows and UTF-8 on Linux and Mac.
Name of the encoding. This will be the lower-case version of one of the IANA official names for the character set (see http://www.iana.org/assignments/character-sets/character-sets.xml)
Gets an Encoding object from the name of the character set name. The names used are the IANA official names for the character set (see http://www.iana.org/assignments/character-sets/character-sets.xml).
The name passed is case insensitive.
If character set is not supported null
is returned.
File objects are references to files.
If path is a symbolic link, rather than a file, then the methods of File operate on the ultimate target of the link, except for File.delete and File.deleteSync, which operate on the link.
To operate on the underlying file data there are two options:
Get a Directory object for the directory containing this file.
Get the path of the file.
Create a File object.
Create a File object from a Path object.
Create the file. Returns a Future<File>
that completes with the file when it has been created.
Existing files are left untouched by create. Calling create on an existing file might fail if there are restrictive permissions on the file.
Synchronously create the file. Existing files are left untouched by createSync. Calling createSync on an existing file might fail if there are restrictive permissions on the file.
Throws a FileIOException if the operation fails.
Delete the file. Returns a Future<File>
that completes with the file when it has been deleted. Only a file or a link to a file can be deleted with this method, not a directory or a broken link.
Synchronously delete the file. Only a file or a link to a file can be deleted with this method, not a directory or a broken link.
Throws a FileIOException if the operation fails.
Get the canonical full path corresponding to the file path. Returns a Future<String>
that completes with the path.
Synchronously get the canonical full path corresponding to the file path.
Throws a FileIOException if the operation fails.
Get the last-modified time of the file. Returns a Future<DateTime>
that completes with a DateTime object for the modification date.
Get the last-modified time of the file. Throws an exception if the file does not exist.
Throws a FileIOException if the operation fails.
Get the length of the file. Returns a Future<int>
that completes with the length in bytes.
Synchronously get the length of the file.
Throws a FileIOException if the operation fails.
Open the file for random access operations. Returns a Future<RandomAccessFile>
that completes with the opened random access file. RandomAccessFiles must be closed using the RandomAccessFile.close method.
Files can be opened in three modes:
FileMode.READ: open the file for reading.
FileMode.WRITE: open the file for both reading and writing and truncate the file to length zero. If the file does not exist the file is created.
FileMode.APPEND: same as FileMode.WRITE except that the file is not truncated.
Create a new independent Stream for the contents of this file.
If start is present, the file will be read from byte-offset start. Otherwise from the beginning (index 0).
If end is present, only up to byte-index end will be read. Otherwise, until end of file.
In order to make sure that system resources are freed, the stream must be read to completion or the subscription on the stream must be cancelled.
Synchronously open the file for random access operations. The result is a RandomAccessFile on which random access operations can be performed. Opened RandomAccessFiles must be closed using the RandomAccessFile.close method.
See open for information on the mode argument.
Throws a FileIOException if the operation fails.
Creates a new independent IOSink for the file. The IOSink must be closed when no longer used, to free system resources.
An IOSink for a file can be opened in two modes:
When writing strings through the returned IOSink the encoding specified using encoding will be used. The returned IOSink has an encoding
property which can be changed after the IOSink has been created.
Read the entire file contents as a list of bytes. Returns a Future<List<int>>
that completes with the list of bytes that is the contents of the file.
Synchronously read the entire file contents as a list of bytes.
Throws a FileIOException if the operation fails.
Read the entire file contents as lines of text using the given Encoding.
Returns a Future<List<String>>
that completes with the lines once the file contents has been read.
Synchronously read the entire file contents as lines of text using the given Encoding.
Throws a FileIOException if the operation fails.
Read the entire file contents as a string using the given Encoding.
Returns a Future<String>
that completes with the string once the file contents has been read.
Synchronously read the entire file contents as a string using the given Encoding.
Throws a FileIOException if the operation fails.
Write a list of bytes to a file.
Opens the file, writes the list of bytes to it, and closes the file. Returns a Future<File>
that completes with this File object once the entire operation has completed.
By default writeAsBytes creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.APPEND as the optional mode parameter.
Synchronously write a list of bytes to a file.
Opens the file, writes the list of bytes to it and closes the file.
By default writeAsBytesSync creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.APPEND as the optional mode parameter.
Throws a FileIOException if the operation fails.
Write a string to a file.
Opens the file, writes the string in the given encoding, and closes the file. Returns a Future<File>
that completes with this File object once the entire operation has completed.
By default writeAsString creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.APPEND as the optional mode parameter.
Synchronously write a string to a file.
Opens the file, writes the string in the given encoding, and closes the file.
By default writeAsStringSync creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.APPEND as the optional mode parameter.
Throws a FileIOException if the operation fails.
Returns a string representation of this object.
FileMode describes the modes in which a file can be opened.
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.
The time of the last access to the data of the file system object. On Windows platforms, this may have 1 day granularity, and be out of date by an hour.
The time of the last change to the data or metadata of the file system object. On Windows platforms, this is instead the file creation time.
The mode of the file system object. Permissions are encoded in the lower 16 bits of this number, and can be decoded using the modeString getter.
The time of the last change to the data of the file system object.
The size of the file system object.
The type of the object (file, directory, or link). If the call to stat() fails, the type of the returned object is NOT_FOUND.
Returns the mode value as a human-readable string, in the format "rwxrwxrwx", reflecting the user, group, and world permissions to read, write, and execute the file system object, with "-" replacing the letter for missing permissions. Extra permission bits may be represented by prepending "(suid)", "(guid)", and/or "(sticky)" to the mode string.
Asynchronously calls the operating system's stat() function on path. Returns a Future which completes with a FileStat object containing the data returned by stat(). If the call fails, completes the future with a FileStat object with .type set to FileSystemEntityType.NOT_FOUND and the other fields invalid.
Calls the operating system's stat() function on path. Returns a FileStat object containing the data returned by stat(). If the call fails, returns a FileStat object with .type set to FileSystemEntityType.NOT_FOUND and the other fields invalid.
Returns a string representation of this object.
A FileSystemEntity is a common super class for File and Directory objects.
FileSystemEntity objects are returned from directory listing operations. To determine if a FileSystemEntity is a File or a Directory, perform a type check:
if (entity is File) (entity as File).readAsStringSync();
Checks whether the file system entity with this path exists. Returns a Future<bool>
that completes with the result.
Since FileSystemEntity is abstract, every FileSystemEntity object is actually an instance of one of the subclasses File, Directory, and Link. Calling exists on an instance of one of these subclasses checks whether the object exists in the file system object exists and is of the correct type (file, directory, or link). To check whether a path points to an object on the file system, regardless of the object's type, use the type static method.
Synchronously checks whether the file system entity with this path exists.
Since FileSystemEntity is abstract, every FileSystemEntity object is actually an instance of one of the subclasses File, Directory, and Link. Calling existsSync on an instance of one of these subclasses checks whether the object exists in the file system object exists and is of the correct type (file, directory, or link). To check whether a path points to an object on the file system, regardless of the object's type, use the typeSync static method.
Synchronously checks whether two paths refer to the same object in the file system. Returns a Future<bool>
that completes with the result.
Comparing a link to its target returns false, as does comparing two links that point to the same target. To check the target of a link, use Link.target explicitly to fetch it. Directory links appearing inside a path are followed, though, to find the file system object.
Completes the returned Future with an error if one of the paths points to an object that does not exist.
Synchronously checks whether two paths refer to the same object in the file system.
Comparing a link to its target returns false, as does comparing two links that point to the same target. To check the target of a link, use Link.target explicitly to fetch it. Directory links appearing inside a path are followed, though, to find the file system object.
Throws an error if one of the paths points to an object that does not exist.
Checks if type(path) returns FileSystemEntityType.DIRECTORY.
Synchronously checks if typeSync(path) returns FileSystemEntityType.DIRECTORY.
Checks if type(path) returns FileSystemEntityType.FILE.
Synchronously checks if typeSync(path) returns FileSystemEntityType.FILE.
Checks if type(path, followLinks: false) returns FileSystemEntityType.LINK.
Synchronously checks if typeSync(path, followLinks: false) returns FileSystemEntityType.LINK.
Calls the operating system's stat() function on the path of this FileSystemEntity. Identical to FileStat.stat(this.path)
.
Returns a Future<FileStat>
object containing the data returned by stat().
If the call fails, completes the future with a FileStat object with .type set to FileSystemEntityType.NOT_FOUND and the other fields invalid.
Synchronously calls the operating system's stat() function on the path of this FileSystemEntity. Identical to FileStat.statSync(this.path)
.
Returns a FileStat object containing the data returned by stat().
If the call fails, returns a FileStat object with .type set to FileSystemEntityType.NOT_FOUND and the other fields invalid.
Finds the type of file system object that a path points to. Returns a Future<FileSystemEntityType>
that completes with the result.
FileSystemEntityType has the constant instances FILE, DIRECTORY, LINK, and NOT_FOUND. type will return LINK only if the optional named argument followLinks is false, and path points to a link. If the path does not point to a file system object, or any other error occurs in looking up the path, NOT_FOUND is returned. The only error or exception that may be put on the returned future is ArgumentError, caused by passing the wrong type of arguments to the function.
Synchronously finds the type of file system object that a path points to. Returns a FileSystemEntityType.
FileSystemEntityType has the constant instances FILE, DIRECTORY, LINK, and NOT_FOUND. type will return LINK only if the optional named argument followLinks is false, and path points to a link. If the path does not point to a file system object, or any other error occurs in looking up the path, NOT_FOUND is returned. The only error or exception that may be thrown is ArgumentError, caused by passing the wrong type of arguments to the function.
Returns a string representation of this object.
Representation of a header value in the form:
value; parameter1=value1; parameter2=value2
HeaderValue can be used to conveniently build and parse header values on this form.
To build an accepts
header with the value
text/plain; q=0.3, text/htmluse code like this:
HttpClientRequest request = ...; var v = new HeaderValue("text/plain", {"q": "0.3"}); request.headers.add(HttpHeaders.ACCEPT, v); request.headers.add(HttpHeaders.ACCEPT, "text/html");To parse the header values use the
parse
static method.
HttpRequest request = ...; List<String> values = request.headers[HttpHeaders.ACCEPT]; values.forEach((value) { HeaderValue v = HeaderValue.parse(value); // Use v.value and v.parameters });An instance of HeaderValue is immutable.
Gets the map of parameters.
Gets the header value.
Creates a new header value object setting the value part.
Creates a new header value object from parsing a header value string with both value and optional parameters.
Returns the formatted string representation in the form:
value; parameter1=value1; parameter2=value2
A HTTP content body produced by HttpBodyHandler for either HttpRequest or HttpClientResponse.
The actual body. The type depends on type.
The content type e.g. application/json, application/octet-stream, application/x-www-form-urlencoded, text/plain.
A high-level type value, that reflects how the body was parsed, e.g. "text", "binary" and "json".
A HttpBodyFileUpload object wraps a file upload, presenting a way for extracting filename, contentType and the data of the uploaded file.
The content of the file. Either a String or a List<int>.
The ContentType of the uploaded file. For 'text/\*' and 'application/json' the data field will a String.
The filename of the uploaded file.
HttpBodyHandler is a helper class for parsing and collecting HTTP message data in an easy-to-use HttpBody object. The content body is parsed, depending on the 'Content-Type' header field.
To use with the HttpServer for request messages, HttpBodyHandler can be used as either a StreamTransformer or as a per-request handler (see processRequest()).
HttpServer server = ... server.transform(new HttpBodyHandler()) .listen((HttpRequestBody body) { ... });To use with the HttpClient for response messages, HttpBodyHandler can be used as a per-request handler (see processResponse()).
HttpClient client = ... client.get(...) .then((HttpClientRequest response) => response.close()) .then(HttpBodyHandler.processResponse) .then((HttpClientResponseBody body) { ... });The following mime-types will be handled specially: - text/\* - application/json
All other mime-types will be returned as List<int>.
Create a new HttpBodyHandler to be used with a Stream<HttpRequest>, e.g. a HttpServer.
If the page was served using different encoding than UTF-8, set defaultEncoding accordingly. This is required for parsing 'application/x-www-form-urlencoded' content correctly.
Process and parse an incoming HttpRequest. The returned HttpRequestBody contains a response field for accessing the HttpResponse.
See HttpBodyHandler constructor for more info on defaultEncoding.
Process and parse an incoming HttpClientResponse.
See HttpBodyHandler constructor for more info on defaultEncoding.
The HttpClient class implements the client side of the HTTP protocol. It contains a number of methods to send a HTTP request to a HTTP server and receive a HTTP response back.
This is a two-step process, triggered by two futures. When the first future completes with a HttpClientRequest the underlying network connection has been established, but no data has yet been sent. The HTTP headers and body can be set on the request, and close
is called to sent it to the server.
The second future, which is returned by close
, completes with an HttpClientResponse object when the response is received from the server. This object contains the headers and body of the response.
The future for HttpClientRequest is created by methods such as getUrl() and open().
When the HTTP response is ready a HttpClientResponse object is provided which provides access to the headers and body of the response.
HttpClient client = new HttpClient(); client.getUrl(Uri.parse("http://www.example.com/")) .then((HttpClientRequest request) { // Prepare the request then call close on it to send it. return request.close(); }) .then((HttpClientResponse response) { // Process the response. });All HttpClient requests set the following header by default:
Accept-Encoding: gzipThis allows the HTTP server to use gzip compression for the body if possible. If this behavior is not desired set the "Accept-Encoding" header to something else.
The HttpClient supports persistent connections and caches network connections to reuse then for multiple requests whenever possible. This means that network connections can be kept open for some time after a request have completed. Use HttpClient.close
to force shut down the HttpClient object and close the idle network connections.
By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment(). To turn off the use of proxies all together set the findProxy property to null
.
HttpClient client = new HttpClient(); client.findProxy = null;
Get and set the idle timeout of non-active persistent (keep-alive) connections. The default value is 15 seconds.
Sets the function to be called when a site is requesting authentication. The URL requested and the security realm from the server are passed in the arguments url and realm.
The function returns a Future which should complete when the authentication has been resolved. If credentials cannot be provided the Future should complete with false. If credentials are available the function should add these using addCredentials before completing the Future with the value true.
If the Future completes with true the request will be retried using the updated credentials. Otherwise response processing will continue normally.
Sets the function to be called when a proxy is requesting authentication. Information on the proxy in use and the security realm for the authentication are passed in the arguments host, port and realm.
The function returns a Future which should complete when the authentication has been resolved. If credentials cannot be provided the Future should complete with false. If credentials are available the function should add these using addProxyCredentials before completing the Future with the value true.
If the Future completes with true the request will be retried using the updated credentials. Otherwise response processing will continue normally.
Sets the function used to resolve the proxy server to be used for opening a HTTP connection to the specified url. If this function is not set, direct connections will always be used.
The string returned by f must be in the format used by browser PAC (proxy auto-config) scripts. That is either
"DIRECT"
for using a direct connection or
"PROXY host:port"
for using the proxy server host
on port port
.
A configuration can contain several configuration elements separated by semicolons, e.g.
"PROXY host:port; PROXY host2:port2; DIRECT"
The static function findProxyFromEnvironment on this class can be used to implement proxy server resolving based on environment variables.
Add credentials to be used for authorizing HTTP requests.
Add credentials to be used for authorizing HTTP proxies.
Shutdown the HTTP client. If force is false
(the default) the HttpClient
will be kept alive until all active connections are done. If force is true
any active connections will be closed to immediately release all resources. These closed connections will receive an onError
callback to indicate that the client was shutdown. In both cases trying to establish a new connection after calling shutdown will throw an exception.
Function for resolving the proxy server to be used for a HTTP connection from the proxy configuration specified through environment variables.
The following environment variables are taken into account:
http_proxy https_proxy no_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY
http_proxy
and HTTP_PROXY
specify the proxy server to use for http:// urls. Use the format hostname:port
. If no port is used a default of 1080 will be used. If both are set the lower case one takes precedence.
https_proxy
and HTTPS_PROXY
specify the proxy server to use for https:// urls. Use the format hostname:port
. If no port is used a default of 1080 will be used. If both are set the lower case one takes precedence.
no_proxy
and NO_PROXY
specify a comma separated list of postfixes of hostnames for which not to use the proxy server. E.g. the value "localhost,<IP_ADDRESS>" will make requests to both "localhost" and "<IP_ADDRESS>" not use a proxy. If both are set the lower case one takes precedence.
To activate this way of resolving proxies assign this function to the findProxy property on the HttpClient.
HttpClient client = new HttpClient(); client.findProxy = HttpClient.findProxyFromEnvironment;If you don't want to use the system environment you can use a different one by wrapping the function.
HttpClient client = new HttpClient(); client.findProxy = (url) { return HttpClient.findProxyFromEnvironment( url, {"http_proxy": ..., "no_proxy": ...}); }If a proxy requires authentication it is possible to configure the username and password as well. Use the format
username:password@hostname:port
to include the username and password. Alternatively the API addProxyCredentials can be used to set credentials for proxies which require authentication.
Opens a HTTP connection using the GET method. See open for details. Using this method to open a HTTP connection will set the content length to 0.
Opens a HTTP connection using the GET method. See openUrl for details. Using this method to open a HTTP connection will set the content length to 0.
Opens a HTTP connection. The returned HttpClientRequest is used to fill in the content of the request before sending it. The 'host' header for the request will be set to the value host:port. This can be overridden through the HttpClientRequest interface before the request is sent. NOTE if host is an IP address this will still be set in the 'host' header.
Opens a HTTP connection. The returned HttpClientRequest is used to fill in the content of the request before sending it. The 'hosth header for the request will be set to the value host:port. This can be overridden through the HttpClientRequest interface before the request is sent. NOTE if host is an IP address this will still be set in the 'host' header.
Opens a HTTP connection using the POST method. See open for details.
Opens a HTTP connection using the POST method. See openUrl for details.
Represents credentials for basic authentication.
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".
HTTP request for a client connection.
This object has a number of properties for setting up the HTTP header of the request. When the header has been set up the methods from the IOSink can be used to write the actual body of the HTTP request. When one of the IOSink methods is used for the first time the request header is send. Calling any methods that will change the header after it is sent will throw an exception.
When writing string data through the IOSink the encoding used will be determined from the "charset" parameter of the "Content-Type" header.
HttpClientRequest request = ... request.headers.contentType = new ContentType("application", "json", charset: "utf-8"); request.write(...); // Strings written will be UTF-8 encoded.If no charset is provided the default of ISO-8859-1 (Latin 1) will be used.
HttpClientRequest request = ... request.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain"); request.write(...); // Strings written will be ISO-8859-1 encoded.If an unsupported encoding is used an exception will be thrown if using one of the write methods taking a string.
Gets and sets the content length of the request. If the size of the request is not known in advance set content length to -1, which is also the default.
Set this property to true
if this request should automatically follow redirects. The default is true
.
Automatic redirect will only happen for "GET" and "HEAD" requests and only for the status codes HttpHeaders.MOVED_PERMANENTLY
(301), HttpStatus.FOUND
(302), HttpStatus.MOVED_TEMPORARILY
(302, alias for HttpStatus.FOUND
), HttpStatus.SEE_OTHER
(303) and HttpStatus.TEMPORARY_REDIRECT
(307). For HttpStatus.SEE_OTHER
(303) autmatic redirect will also happen for "POST" requests with the method changed to "GET" when following the redirect.
All headers added to the request will be added to the redirection request(s). However, any body send with the request will not be part of the redirection request(s).
Set this property to the maximum number of redirects to follow when followRedirects is true
. If this number is exceeded the onError callback will be called with a RedirectLimitExceeded exception. The default value is 5.
Gets and sets the requested persistent connection state. The default value is true
.
Get information about the client connection. Returns null if the socket is not available.
Cookies to present to the server (in the 'cookie' header).
A HttpClientResponse future that will complete once the response is available. If an error occurs before the response is available, this future will complete with an error.
Returns the request headers.
The method of the request.
The uri of the request.
Close the request for input. Returns the value of done.
HTTP response for a client connection. The HttpClientResponse is a Stream of the body content of the response. Listen to the body to handle the data and be notified once the entire body is received.
Returns the certificate of the HTTPS server providing the response. Returns null if the connection is not a secure TLS or SSL connection.
Gets information about the client connection. Returns null if the socket is not available.
Returns the content length of the request body. Returns -1 if the size of the request body is not known in advance.
Cookies set by the server (from the 'set-cookie' header).
Returns the response headers.
Returns whether the status code is one of the normal redirect codes HttpStatus.MOVED_PERMANENTLY, HttpStatus.FOUND, HttpStatus.MOVED_TEMPORARILY, HttpStatus.SEE_OTHER and HttpStatus.TEMPORARY_REDIRECT.
Gets the persistent connection state returned by the server.
Returns the reason phrase associated with the status code.
Returns the series of redirects this connection has been through. The list will be empty if no redirects were followed. redirects will be updated both in the case of an automatic and a manual redirect.
Returns the status code.
Detach the underlying socket from the HTTP client. When the socket is detached the HTTP client will no longer perform any operations on it.
This is normally used when a HTTP upgrade is negotiated and the communication should continue with a different protocol.
Redirects this connection to a new URL. The default value for method is the method for the current request. The default value for url is the value of the HttpHeaders.LOCATION header of the current response. All body data must have been read from the current response before calling redirect.
All headers added to the request will be added to the redirection request. However, any body sent with the request will not be part of the redirection request.
If followLoops is set to true, redirect will follow the redirect, even if the URL was already visited. The default value is false.
redirect will ignore maxRedirects and will always perform the redirect.
The HttpBody of a HttpClientResponse will be of type HttpClientResponseBody. It contains the HttpClientResponse object for access to the headers.
Returns the response headers.
Returns the reason phrase associated with the status code.
The HttpClientResponse of the HTTP body.
Returns the status code.
Information about an HttpRequest, HttpResponse, HttpClientRequest, or HttpClientResponse connection.
Summary statistics about an HttpServers current socket connections.
Number of active connections where actual request/response processing is active.
Number of connections which are preparing to close. Note: These connections are also part of the active
count as they might still be sending data to the client before finally closing.
Number of idle connections held by clients as persistent connections.
Total number of socket connections.
Returns a string representation of this object.
Access to the HTTP headers for requests and responses. In some situations the headers will be immutable and the mutating methods will then throw exceptions.
For all operations on HTTP headers the header name is case-insensitive.
Gets and sets the chunked transfer encoding header value.
Gets and sets the content length header value.
Gets and sets the content type. Note that the content type in the header will only be updated if this field is set directly. Mutating the returned current value will have no effect.
Gets and sets the date. The value of this property will reflect the 'date' header.
Gets and sets the expiry date. The value of this property will reflect the 'expires' header.
Gets and sets the host part of the 'host' header for the connection.
Gets and sets the "if-modified-since" date. The value of this property will reflect the "if-modified-since" header.
Gets and sets the persistent connection header value.
Gets and sets the port part of the 'host' header for the connection.
Returns the list of values for the header named name. If there is no header with the provided name, null
will be returned.
Adds a header value. The header named name will have the value value added to its list of values. Some headers are single valued, and for these adding a value will replace the previous value. If the value is of type DateTime a HTTP date format will be applied. If the value is a List
each element of the list will be added separately. For all other types the default toString
method will be used.
Enumerates the headers, applying the function f to each header. The header name passed in name
will be all lower case.
Disables folding for the header named name when sending the HTTP header. By default, multiple header values are folded into a single header line by separating the values with commas. The 'set-cookie' header has folding disabled by default.
Removes a specific value for a header name. Some headers have system supplied values and for these the system supplied values will still be added to the collection of values for the header.
Removes all values for the specified header name. Some headers have system supplied values and for these the system supplied values will still be added to the collection of values for the header.
Sets a header. The header named name will have all its values cleared before the value value is added as its value.
Convenience method for the value for a single valued header. If there is no header with the provided name, null
will be returned. If the header has more than one value an exception is thrown.
HttpMultipartFormData
class used for 'upgrading' a MimeMultipart by parsing it as a 'multipart/form-data' part. The following code shows how it can be used.
HttpServer server = ...; server.listen((request) {
String boundary = request.headers.contentType.parameters['boundary']; request .transform(new MimeMultipartTransformer(boundary)) .map(HttpMultipartFormData.parse) .map((HttpMultipartFormData formData) { // form data object available here. });
HttpMultipartFormData
is a Stream, serving either bytes or decoded Strings. Use isText or isBinary to see what type of data is provided.
The parsed Content-Disposition
header of the HttpMultipartFormData
. This field is always present. Use this to extract e.g. name(form field name)and filename (client provided name of uploaded file) parameters.
The parsed Content-Transfer-Encoding
header of the HttpMultipartFormData
. This field is used to determine how to decode the data. Returns null
if not present.
The parsed Content-Type
header of the HttpMultipartFormData
. Returns null
if not present.
Returns true
if the data is raw bytes.
Returns true
if the data is decoded as String.
Parse a MimeMultipart and return a HttpMultipartFormData. If the Content-Disposition
header is missing or invalid, a HttpException is thrown.
Returns the value for the header named name. If there is no header with the provided name, null
will be returned.
Use this method to index other headers available in the original MimeMultipart.
Returns a string representation of this object.
Http request delivered to the HTTP server callback. The HttpRequest is a Stream of the body content of the request. Listen to the body to handle the data and be notified once the entire body is received.
Returns the client certificate of the client making the request. Returns null if the connection is not a secure TLS or SSL connection, or if the server does not request a client certificate, or if the client does not provide one.
Gets information about the client connection. Returns null if the socket is not available.
Returns the content length of the request body. If the size of the request body is not known in advance this -1.
Returns the cookies in the request (from the Cookie headers).
Returns the request headers.
Returns the method for the request.
Returns the persistent connection state signaled by the client.
Returns the HTTP protocol version used in the request. This will be "1.0" or "1.1".
Gets the HttpResponse object, used for sending back the response to the client.
If the contentLength of the body isn't 0, and the body isn't being read, any write calls on the HttpResponse will automatically drain the request body.
Gets the session for the given request. If the session is being initialized by this call, isNew
will be true for the returned session. See HttpServer.sessionTimeout on how to change default timeout.
Returns the URI for the request. This provides access to the path, query string and fragment identifier for the request.
The HttpBody of a HttpRequest will be of type HttpRequestBody. It contains the fields used to read all request header information and responding to the client.
Returns the request headers.
Returns the method for the request.
The HttpResponse used for responding to the client.
Returns the URI for the request.
An HttpResponse represents the headers and data to be returned to a client in response to an HTTP request.
This object has a number of properties for setting up the HTTP header of the response. When the header has been set up the methods from the IOSink can be used to write the actual body of the HTTP response. When one of the IOSink methods is used for the first time the request header is send. Calling any methods that will change the header after it is sent will throw an exception.
When writing string data through the IOSink the encoding used will be determined from the "charset" parameter of the "Content-Type" header.
HttpResponse response = ... response.headers.contentType = new ContentType("application", "json", charset: "utf-8"); response.write(...); // Strings written will be UTF-8 encoded.If no charset is provided the default of ISO-8859-1 (Latin 1) will be used.
HttpResponse response = ... response.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain"); response.write(...); // Strings written will be ISO-8859-1 encoded.If an unsupported encoding is used an exception will be thrown if using one of the write methods taking a string.
Gets and sets the content length of the response. If the size of the response is not known in advance set the content length to -1 - which is also the default if not set.
Gets and sets the persistent connection state. The initial value of this property is the persistent connection state from the request.
Gets and sets the reason phrase. If no reason phrase is explicitly set a default reason phrase is provided.
Gets and sets the status code. Any integer value is accepted. For the official HTTP status codes use the fields from HttpStatus. If no status code is explicitly set the default value HttpStatus.OK is used.
Gets information about the client connection. Returns null if the socket is not available.
Cookies to set in the client (in the 'set-cookie' header).
Returns the response headers.
Detaches the underlying socket from the HTTP server. When the socket is detached the HTTP server will no longer perform any operations on it.
This is normally used when a HTTP upgrade request is received and the communication should continue with a different protocol.
HTTP server.
Returns the port that the server is listening on. This can be used to get the actual port used when a value of 0 for port
is specified in the bind or bindSecure call.
Sets the timeout, in seconds, for sessions of this HttpServer. The default timeout is 20 minutes.
Attaches the HTTP server to an existing ServerSocket. When the HttpServer is closed, the HttpServer will just detach itself, closing current connections but not closing serverSocket.
Starts listening for HTTP requests on the specified address and port.
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 to bind to all interfaces or the IP address of a specific interface.
If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use HttpServer.listenOn with a ServerSocket configured for IP version 6 connections only.
If port has the value 0
an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.
The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0
(the default) a reasonable value will be chosen by the system.
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 to bind to all interfaces or the IP address of a specific interface.
If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use HttpServer.listenOn with a ServerSocket configured for IP version 6 connections only.
If port has the value 0
an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.
The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0
(the default) a reasonable value will be chosen by the system.
The certificate with Distinguished Name certificateName is looked up in the certificate database, and is used as the server certificate. if requestClientCertificate is true, the server will request clients to authenticate with a client certificate.
Permanently stops this HttpServer from listening for new connections. This closes this Stream of HttpRequests with a done event.
Returns an HttpConnectionsInfo object summarizing the number of current connections handled by the server.
Gets the id for the current session.
Is true if the session has not been sent to the client yet.
Sets a callback that will be called when the session is timed out.
Destroys the session. This will terminate the session and any further connections with this id will be given a new id and session.
HTTP status codes.
Helper class to wrap a StreamConsumer<List<int>> and provide utility functions for writing to the StreamConsumer directly. The IOSink buffers the input given by all StringSink methods and will delay a addStream() until the buffer is flushed.
When the IOSink is bound to a stream (through addStream()) any call to the IOSink will throw a StateError. When the addStream() compeltes, the IOSink will again be open for all calls.
The Encoding used when writing strings. Depending on the underlying consumer this property might be mutable.
Get a future that will complete when all synchronous have completed, or an error happened. This future is identical to the future returned from close.
Writes the bytes uninterpreted to the consumer.
Writes an error to the consumer.
Adds all elements of the given stream to this
.
Close the target.
The InternetAddress is an object reflecting either a remote or a local address. When combined with a port number, this represents a endpoint that a socket can connect to or a listening socket can bind to.
The type of the InternetAddress specified what IP protocol.
IP version 4 any address. Use this address when listening on all adapters IP addresses using IP version 4 (IPv4).
IP version 6 any address. Use this address when listening on all adapters IP addresses using IP version 6 (IPv6).
IP version 4 loopback address. Use this address when listening on or connecting to the loopback adapter using IP version 4 (IPv4).
IP version 6 loopback address. Use this address when listening on or connecting to the loopback adapter using IP version 6 (IPv6).
The resolved address of the host.
The host used to lookup the address.
Lookup a host, returning a Future of a list of InternetAddresss. If type is InternetAddressType.ANY, it will lookup both IP version 4 (IPv4) and IP version 6 (IPv6) addresses. If type is either InternetAddressType.IP_V4 or InternetAddressType.IP_V6 it will only lookup addresses of the specified type. The order of the list can, and most likely will, change over time.
InternetAddressType is the type an InternetAddress. Currently, IP version 4 (IPv4) and IP version 6 (IPv6) are supported.
Get the name of the type, e.g. "IP_V4" or "IP_V6".
Returns a string representation of this object.
Act on incoming data event.
The method may generate any number of events on the sink, but should not throw.
Act on incoming done event.
The method may generate any number of events on the sink, but should not throw.
Link objects are references to filesystem links.
Creates a Link object.
Creates a Link object from a Path object.
Creates a symbolic link. Returns a Future<Link>
that completes with the link when it has been created. If the link exists, the future will complete with an error.
On the Windows platform, this will only work with directories, and the target directory must exist. The link will be created as a Junction. Only absolute links will be created, and relative paths to the target will be converted to absolute paths.
On other platforms, the posix symlink() call is used to make a symbolic link containing the string target. If target is a relative path, it will be interpreted relative to the directory containing the link.
Synchronously create the link. Calling createSync on an existing link will throw an exception.
On the Windows platform, this will only work with directories, and the target directory must exist. The link will be created as a Junction. Only absolute links will be created, and relative paths to the target will be converted to absolute paths.
On other platforms, the posix symlink() call is used to make a symbolic link containing the string target. If target is a relative path, it will be interpreted relative to the directory containing the link.
Deletes the link. Returns a Future<Link>
that completes with the link when it has been deleted. This does not delete, or otherwise affect, the target of the link. It also works on broken links, but if the link does not exist or is not actually a link, it completes the future with a LinkIOException.
Synchronously deletes the link. This does not delete, or otherwise affect, the target of the link. It also works on broken links, but if the link does not exist or is not actually a link, it throws a LinkIOException.
Gets the target of the link. Returns a future that completes with the path to the target.
If the returned target is a relative path, it is relative to the directory containing the link.
If the link does not exist, or is not a link, the future completes with a LinkIOException.
Synchronously gets the target of the link. Returns the path to the target.
If the returned target is a relative path, it is relative to the directory containing the link.
If the link does not exist, or is not a link, throws a LinkIOException.
Synchronously updates the link. Calling updateSync on a non-existing link will throw an exception.
If linkRelative is true, the target argument should be a relative path, and the link will interpret the target as a path relative to the link's directory.
On the Windows platform, this will only work with directories, and the target directory must exist.
Returns a string representation of this object.
A Mime Multipart class representing each part parsed by MimeMultipartTransformer. The data is streamed in as it become available.
Returns a string representation of this object.
Parser for MIME multipart types of data as described in RFC 2046 section 5.1.1. The data is transformed into MimeMultipart objects, each of them streaming the multipart data.
Construct a new MIME multipart parser with the boundary boundary. The boundary should be as specified in the content type parameter, that is without the -- prefix.
An OSError object holds information about an error from the operating system.
Constant used to indicate that no OS error code is available.
Error code supplied by the operating system. Will have the value noErrorCode if there is no error code associated with the error.
Error message supplied by the operating system. null if no message is associated with the error.
Creates an OSError object from a message and an errorCode.
Converts an OSError object to a string representation.
The Options object allows accessing the arguments which have been passed to the current isolate.
Returns a list of arguments that have been passed to this isolate. Any modifications to the list will be contained to the options object owning this list.
If the execution environment does not support arguments an empty list is returned.
Returns the path of the executable used to run the script in this isolate.
If the execution environment does not support executable an empty string is returned.
Returns the path of the script being run in this isolate.
If the executable environment does not support script an empty string is returned.
A newly constructed Options object contains the arguments exactly as they have been passed to the isolate.
A Path is an immutable wrapper of a String, with additional member functions for useful path manipulations and queries. On the Windows platform, Path also converts from native paths to paths using '/' as a path separator, and vice versa.
Joining of paths and path normalization handle '.' and '..' in the usual way.
Drops the final '/' and whatever follows it from this Path, and returns the resulting Path object. If the only '/' in this Path is the first character, returns '/' instead of the empty string. If there is no '/' in the Path, returns the empty string.
new Path('../images/dot.gif').directoryPath == '../images' new Path('/usr/geoffrey/www/').directoryPath == '/usr/geoffrey/www' new Path('lost_file_old').directoryPath == '' new Path('/src').directoryPath == '/' Note: new Path('/D:/src').directoryPath == '/D:'
The part of filename after the last '.', or '' if filename contains no '.'. If filename is '.' or '..', returns ''.
new Path('tiger.svg').extension == 'svg' new Path('/src/dart/dart_secrets').extension == ''
The part of the path after the last '/', or the entire path if it contains no '/'.
new Path('images/DSC_0027.jpg).filename == 'DSC_0027.jpg' new Path('users/fred/').filename == ''
The part of filename before the last '.', or the entire filename if it contains no '.'. If filename is '.' or '..' it is unchanged.
new Path('/c:/My Documents/Heidi.txt').filenameWithoutExtension would return 'Heidi'. new Path('not what I would call a path').filenameWithoutExtension would return 'not what I would call a path'.
Does this path end with a '/'?
Is this path an absolute path, beginning with a '/'? Note that Windows paths beginning with '\' or with a drive letter are absolute, and a leading '/' is added when they are converted to a Path.
Does this path contain no consecutive '/'s, no segments that are '.' unless the path is exactly '.', and segments that are '..' only as the leading segments on a relative path?
Is this path the empty string?
Is this path a Windows share path?
Creates a Path from a String that uses the native filesystem's conventions.
On Windows, this converts '\' to '/' and has special handling for drive letters and shares.
If the path starts with a drive letter, like 'C:', a '/' is added before the drive letter.
new Path(r'c:\a\b').toString() == '/c:/a/b'A path starting with a drive letter is treated specially. Backwards links ('..') cannot cancel the drive letter.
If the path is a share path this is recorded in the Path object and maintained in operations on the Path object.
var share = new Path(r'\\share\a\b\c'); share.isWindowsShare == true share.toString() == '/share/a/b/c' share.toNativePath() == r'\\share\a\b\c' share.append('final').isWindowsShare == true
Creates a Path from the String source. source is used as-is, so if the string does not consist of segments separated by forward slashes, the behavior may not be as expected. Paths are immutable.
Appends finalSegment to a path as a new segment. Adds a '/' between the path and finalSegment if the path does not already end in a '/'. The path is not canonicalized, and finalSegment may contain '/'s.
Make a path canonical by dropping segments that are '.', cancelling segments that are '..' with preceding segments, if possible, and combining consecutive '/'s. Leading '..' segments are kept on relative paths, and dropped from absolute paths.
Joins the relative path further to this path. Canonicalizes the resulting joined path using canonicalize, interpreting '.' and '..' as directory traversal commands, and removing consecutive '/'s.
If further is an absolute path, an IllegalArgument exception is thrown.
Examples: new Path('/a/b/c').join(new Path('d/e'))
returns the Path object containing 'a/b/c/d/e'
.
new Path('a/b/../c/').join(new Path('d/./e//')
returns the Path containing 'a/c/d/e/'
.
new Path('a/b/c').join(new Path('d/../../e')
returns the Path containing 'a/b/e'
.
Note that the join operation does not drop the last segment of the base path, the way URL joining does. To join basepath to further using URL semantics, use basepath.directoryPath.join(further)
.
If you want to avoid joins that traverse parent directories in the base, you can check whether further.canonicalize()
starts with '../' or equals '..'.
Returns a path relative
such that base.join(relative) == this.canonicalize()
. Throws an exception if such a path is impossible. For example, if base is '../../a/b' and this is '.'. The computation is independent of the file system and current directory.
To compute a relative path using URL semantics, where the final path component of the base is dropped unless it ends with a slash, call a.relativeTo(b.directoryPath)
instead of a.relativeTo(b)
.
Gets the segments of a Path. The segments are just the result of splitting the path on any '/' characters, except that a '/' at the beginning does not create an empty segment before it, and a '/' at the end does not create an empty segment after it.
new Path('/a/b/c/d').segments() == ['a', 'b', 'c', d']; new Path(' foo bar //../') == [' foo bar ', '', '..'];
Converts a path to a string using the native filesystem's conventions.
Always returns '.' if the path is empty. On Windows, converts '/'s to backwards slashes, and removes the leading '/' if the path starts with a drive specification. For most valid Windows paths, this should be the inverse of the conversion that the constructor new Path() performs. If the path is a Windows share, restores the '\\' at the start of the path.
Returns the path as a string. If this path is constructed using new Path.raw(), or new Path() on a non-Windows system, the returned value is the original string argument to the constructor.
The Platform class exposes details of the machine and operating system.
Get the environment for this process.
Environment variables on Windows are case-insensitive. The map returned on Windows is therefore case-insensitive and will convert all keys to upper case. On other platforms the returned map is a standard case-sensitive map.
Get the local hostname for the system.
Get the number of processors of the machine.
Get a string ('macos', 'windows', 'linux') representing the operating system.
Get the path separator used by the operating system to separate components in file paths.
Returns a Future
which completes with the exit code of the process when the process completes.
Throws an UnsupportedError if the process is non-interactive.
Returns the process id of the process.
Returns the standard error stream of the process as a Stream
.
Throws an UnsupportedError if the process is non-interactive.
Returns the standard input stream of the process as an IOSink.
Throws an UnsupportedError if the process is non-interactive.
Returns the standard output stream of the process as a Stream
.
Throws an UnsupportedError if the process is non-interactive.
 On Posix systems, kill sends signal to the process. Depending on the signal giving, it'll have different meanings. When the process terminates as a result of calling kill onExit is called.
Returns true
if the process is successfully killed (the signal is successfully sent). Returns false
if the process could not be killed (the signal could not be sent). Usually, a false
return value from kill means that the process is already dead.
Starts a process and runs it non-interactively to completion. The process run is executable with the specified arguments.
Use workingDirectory to set the working directory for the process. Note that the change of directory occurs before executing the process on some platforms, which may have impact when using relative paths for the executable and the arguments.
Use environment to set the environment variables for the process. If not set the environment of the parent process is inherited. Currently, only US-ASCII environment variables are supported and errors are likely to occur if an environment variable with code-points outside the US-ASCII range is passed in.
If runInShell is true, the process will be spawned through a system shell. On Linux and Mac OS, /bin/sh
is used, while %WINDIR%\system32\cmd.exe
is used on Windows.
The encoding used for text on stdout and stderr can be set by changing stdoutEncoding and stderrEncoding. The default encoding is SYSTEM.
Returns a Future<ProcessResult>
that completes with the result of running the process, i.e., exit code, standard out and standard in.
Starts a process running the executable with the specified arguments. Returns a Future<Process>
that completes with a Process instance when the process has been successfully started. That Process object can be used to interact with the process. If the process cannot be started the returned Future completes with an exception.
Use workingDirectory to set the working directory for the process. Note that the change of directory occurs before executing the process on some platforms, which may have impact when using relative paths for the executable and the arguments.
Use environment to set the environment variables for the process. If not set the environment of the parent process is inherited. Currently, only US-ASCII environment variables are supported and errors are likely to occur if an environment variable with code-points outside the US-ASCII range is passed in.
If runInShell is true, the process will be spawned through a system shell. On Linux and Mac OS, /bin/sh
is used, while %WINDIR%\system32\cmd.exe
is used on Windows.
Users must read all data coming on the stdout and stderr streams of processes started with Process.start
. If the user does not read all data on the streams the underlying system resources will not be freed since there is still pending data.
Contains the arguments provided for the process.
Contains the OS error code for the process exception if any.
Contains the executable provided for the process.
Contains the system message for the process exception if any.
Returns a string representation of this object.
ProcessResult represents the result of running a non-interactive process started with Process.run
.
Exit code for the process.
Process id from the process.
Standard error from the process as a string.
Standard output from the process as a string.
On Posix systems, ProcessSignal is used to send a specific signal to a child process, see Process.kill
.
RandomAccessFile provides random access to the data in a file. RandomAccessFile objects are obtained by calling the open
method on a File object.
Gets the path of the file underlying this RandomAccessFile.
Closes the file. Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when it has been closed.
Synchronously closes the file.
Throws a FileIOException if the operation fails.
Flushes the contents of the file to disk. Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when the flush operation completes.
Synchronously flushes the contents of the file to disk.
Throws a FileIOException if the operation fails.
Gets the length of the file. Returns a Future<int>
that completes with the length in bytes.
Synchronously gets the length of the file.
Throws a FileIOException if the operation fails.
Gets the current byte position in the file. Returns a Future<int>
that completes with the position.
Synchronously gets the current byte position in the file.
Throws a FileIOException if the operation fails.
Reads bytes bytes from a file and returns the result as a list of bytes.
Reads a byte from the file. Returns a Future<int>
that completes with the byte, or with -1 if end-of-file has been reached.
Synchronously reads a single byte from the file. If end-of-file has been reached -1 is returned.
Throws a FileIOException if the operation fails.
Reads into an existing List<int> from the file. If start is present, the bytes will be filled into buffer from at index start, otherwise index 0. If end is present, the end - start bytes will be read into buffer, otherwise up to buffer.length. If end == start nothing happends.
Returns a Future<int>
that completes with the number of bytes read.
Synchronously reads into an existing List<int> from the file. If start is present, the bytes will be filled into buffer from at index start, otherwise index 0. If end is present, the end - start bytes will be read into buffer, otherwise up to buffer.length. If end == start nothing happends.
Throws a FileIOException if the operation fails.
Synchronously reads a maximum of bytes bytes from a file and returns the result in a list of bytes.
Throws a FileIOException if the operation fails.
Sets the byte position in the file. Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when the position has been set.
Synchronously sets the byte position in the file.
Throws a FileIOException if the operation fails.
Returns a human-readable string for this RandomAccessFile instance.
Truncates (or extends) the file to length bytes. Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when the truncation has been performed.
Synchronously truncates (or extends) the file to length bytes.
Throws a FileIOException if the operation fails.
Writes a single byte to the file. Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when the write completes.
Synchronously writes a single byte to the file. Returns the number of bytes successfully written.
Throws a FileIOException if the operation fails.
Writes from a List<int> to the file. It will read the buffer from index start to index end. If start is omitted, it'll start from index 0. If end is omitted, it will write to end of buffer.
Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when the write completes.
Synchronously writes from a List<int> to the file. It will read the buffer from index start to index end. If start is omitted, it'll start from index 0. If end is omitted, it will write to the end of buffer.
Throws a FileIOException if the operation fails.
Writes a string to the file using the given Encoding. Returns a Future<RandomAccessFile>
that completes with this RandomAccessFile when the write completes.
Synchronously writes a single string to the file using the given Encoding.
Throws a FileIOException if the operation fails.
The RawSecureServerSocket is a server socket, providing a stream of low-level RawSecureSockets.
See RawSecureSocket for more info.
Returns the port used by this socket.
Returns a future for a RawSecureServerSocket. When the future completes the server socket is bound to the given address and port and has started listening on it.
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 to bind to all interfaces or the IP address of a specific interface.
If port has the value 0
an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.
The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0
(the default) a reasonable value will be chosen by the system.
Incoming client connections are promoted to secure connections, using the server certificate given by certificateName.
address must be given as a numeric address, not a host name.
certificateName is the nickname or the distinguished name (DN) of the certificate in the certificate database. It is looked up in the NSS certificate database set by SecureSocket.setCertificateDatabase. If certificateName contains "CN=", it is assumed to be a distinguished name. Otherwise, it is looked up as a nickname.
To request or require that clients authenticate by providing an SSL (TLS) client certificate, set the optional parameters requestClientCertificate or requireClientCertificate to true. Require implies request, so one doesn't need to specify both. To check whether a client certificate was received, check SecureSocket.peerCertificate after connecting. If no certificate was received, the result will be null.
Closes the socket.
Adds a subscription to this stream.
On each data event from this stream, the subscriber's onData handler is called. If onData is null, nothing happens.
On errors from this stream, the onError handler is given a object describing the error.
If this stream closes, the onDone handler is called.
If cancelOnError is true, the subscription is ended when the first error is reported. The default is false.
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.
Get the peer certificate for a connected RawSecureSocket. If this RawSecureSocket is the server end of a secure socket connection, peerCertificate will return the client certificate, or null, if no client certificate was received. If it is the client end, peerCertificate will return the server's certificate.
Constructs a new secure client socket and connect it to the given host on the given port. The returned Future is completed with the RawSecureSocket when it is connected and ready for subscription.
The certificate provided by the server is checked using the certificate database provided in SecureSocket.initialize, and/or the default built-in root certificates. If sendClientCertificate is set to true, the socket will send a client certificate if one is requested by the server. If certificateName is the nickname of a certificate in the certificate database, that certificate will be sent. If certificateName is null, which is the usual use case, an appropriate certificate will be searched for in the database and sent automatically, based on what the server says it will accept.
onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the RawSecureSocket connection.
Takes an already connected socket and starts client side TLS handshake to make the communication secure. When the returned future completes the RawSecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is prepared for TLS handshake.
If the socket already has a subscription, pass the existing subscription in the subscription parameter. The secure socket will take over the subscription and process any subsequent events.
See connect for more information on the arguments.
Takes an already connected socket and starts server side TLS handshake to make the communication secure. When the returned future completes the RawSecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is going to start the TLS handshake.
If the socket already has a subscription, pass the existing subscription in the subscription parameter. The secure socket will take over the subscription and process any subsequent events.
If some of the data of the TLS handshake has already been read from the socket this data can be passed in the carryOverData parameter. This data will be processed before any other data available on the socket.
See RawSecureServerSocket.bind for more information on the arguments.
A RawServerSocket represents a listening socket, and provides a stream of low-level RawSocket objects, one for each connection made to the listening socket.
See RawSocket for more info.
Returns the port used by this socket.
Returns a future for a RawServerSocket
. When the future completes the server socket is bound to the given address and port and has started listening on it.
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 to bind to all interfaces or the IP address of a specific interface.
If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use v6Only to set version 6 only.
If port has the value 0
an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port
getter.
The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0
(the default) a reasonable value will be chosen by the system.
Closes the socket.
The RawSocket is a low-level interface to a socket, exposing the raw events signaled by the system. It's a Stream of RawSocketEvents.
Set or get, if the RawSocket should listen for RawSocketEvent.READ events. Default is true.
Set or get, if the RawSocket should listen for RawSocketEvent.WRITE events. Default is true. This is a one-shot listener, and writeEventsEnabled must be set to true again to receive another write event.
Returns the InternetAddress used to connect this socket.
Returns the port used by this socket.
Returns the remote host connected to by this socket.
Returns the remote port connected to by this socket.
Returns the number of received and non-read bytes in the socket that can be read.
Closes the socket. Calling close will never throw an exception and calling it several times is supported. Calling close can result in a RawSocketEvent.READ_CLOSED event.
Creates a new socket connection to the host and port and returns a Future that will complete with either a RawSocket once connected or an error if the host-lookup or connection failed.
host can either be a String or an InternetAddress. If host is a String, connect will perform a InternetAddress.lookup and use the first value in the list.
Read up to len bytes from the socket. This function is non-blocking and will only return data if data is available. The number of bytes read can be less then len if fewer bytes are available for immediate reading. If no data is available null is returned.
Use setOption to customize the RawSocket. See SocketOption for available options.
Returns true if the option was set successfully, false otherwise.
Shutdown the socket in the direction. Calling shutdown will never throw an exception and calling it several times is supported. Calling shutdown with either SocketDirection.BOTH or SocketDirection.RECEIVE can result in a RawSocketEvent.READ_CLOSED event.
Writes up to count bytes of the buffer from offset buffer offset to the socket. The number of successfully written bytes is returned. This function is non-blocking and will only write data if buffer space is available in the socket.
Events for the RawSocket.
Returns a string representation of this object.
Redirect information.
Returns the location for the redirect.
Returns the method used for the redirect.
Returns the status code used for the redirect.
The SecureServerSocket is a server socket, providing a stream of high-level Sockets.
See SecureSocket for more info.
Returns the port used by this socket.
Returns a future for a SecureServerSocket. When the future completes the server socket is bound to the given address and port and has started listening on it.
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 to bind to all interfaces or the IP address of a specific interface.
If port has the value 0
an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.
The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0
(the default) a reasonable value will be chosen by the system.
Incoming client connections are promoted to secure connections, using the server certificate given by certificateName.
address must be given as a numeric address, not a host name.
certificateName is the nickname or the distinguished name (DN) of the certificate in the certificate database. It is looked up in the NSS certificate database set by SecureSocket.setCertificateDatabase. If certificateName contains "CN=", it is assumed to be a distinguished name. Otherwise, it is looked up as a nickname.
To request or require that clients authenticate by providing an SSL (TLS) client certificate, set the optional parameter requestClientCertificate or requireClientCertificate to true. Requiring a certificate implies requesting a certificate, so one doesn't need to set both to true. To check whether a client certificate was received, check SecureSocket.peerCertificate after connecting. If no certificate was received, the result will be null.
Closes the socket.
Adds a subscription to this stream.
On each data event from this stream, the subscriber's onData handler is called. If onData is null, nothing happens.
On errors from this stream, the onError handler is given a object describing the error.
If this stream closes, the onDone handler is called.
If cancelOnError is true, the subscription is ended when the first error is reported. The default is false.
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.
Get the peer certificate for a connected SecureSocket. If this SecureSocket is the server end of a secure socket connection, peerCertificate will return the client certificate, or null, if no client certificate was received. If it is the client end, peerCertificate will return the server's certificate.
Constructs a new secure client socket and connect it to the given host on port port. The returned Future will complete with a SecureSocket that is connected and ready for subscription.
If sendClientCertificate is set to true, the socket will send a client certificate if one is requested by the server.
If certificateName is the nickname of a certificate in the certificate database, that certificate will be sent.
If certificateName is null, which is the usual use case, an appropriate certificate will be searched for in the database and sent automatically, based on what the server says it will accept.
onBadCertificate is an optional handler for unverifiable certificates. The handler receives the X509Certificate, and can inspect it and decide (or let the user decide) whether to accept the connection or not. The handler should return true to continue the SecureSocket connection.
Initializes the NSS library. If initialize is not called, the library is automatically initialized as if initialize were called with no arguments.
The optional argument database is the path to a certificate database directory containing root certificates for verifying certificate paths on client connections, and server certificates to provide on server connections. The argument password should be used when creating secure server sockets, to allow the private key of the server certificate to be fetched. If useBuiltinRoots is true (the default), then a built-in set of root certificates for trusted certificate authorities is merged with the certificates in the database. The list of built-in root certificates, and documentation about this default database, is available at http://www.mozilla.org/projects/security/certs/included/ .
If the database argument is omitted, then only the builtin root certificates are used. If useBuiltinRoots is also false, then no certificates are available.
Examples: 1) Use only the builtin root certificates:
SecureSocket.initialize(); or2) Use a specified database directory and the builtin roots:
SecureSocket.initialize(database: 'path/to/my/database', password: 'my_password');3) Use a specified database directory, without builtin roots:
SecureSocket.initialize(database: 'path/to/my/database', password: 'my_password'. useBuiltinRoots: false);The database should be an NSS certificate database directory containing a cert9.db file, not a cert8.db file. This version of the database can be created using the NSS certutil tool with "sql:" in front of the absolute path of the database directory, or setting the environment variable [NSS_DEFAULT_DB_TYPE] to "sql".
Takes an already connected socket and starts client side TLS handshake to make the communication secure. When the returned future completes the SecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is prepared for TLS handshake.
If the socket already has a subscription, this subscription will no longer receive and events. In most cases calling pause
on this subscription before starting TLS handshake is the right thing to do.
If the host argument is passed it will be used as the host name for the TLS handshake. If host is not passed the host name from the socket will be used. The host can be either a String or an InternetAddress.
See connect for more information on the arguments.
Takes an already connected socket and starts server side TLS handshake to make the communication secure. When the returned future completes the SecureSocket has completed the TLS handshake. Using this function requires that the other end of the connection is going to start the TLS handshake.
If the socket already has a subscription, this subscription will no longer receive and events. In most cases calling pause
on this subscription before starting TLS handshake is the right thing to do.
If some of the data of the TLS handshake has already been read from the socket this data can be passed in the carryOverData parameter. This data will be processed before any other data available on the socket.
See SecureServerSocket.bind for more information on the arguments.
A ServerSocket represents a listening socket, and provides a stream of Socket objects, one for each connection made to the listening socket.
See Socket for more info.
Returns the port used by this socket.
Returns a future for a ServerSocket
. When the future completes the server socket is bound to the given address and port and has started listening on it.
The address can either be a String or an InternetAddress. If address is a String, bind will perform a InternetAddress.lookup and use the first value in the list. To listen on the loopback adapter, which will allow only incoming connections from the local host, use the value InternetAddress.LOOPBACK_IP_V4 or InternetAddress.LOOPBACK_IP_V6. To allow for incoming connection from the network use either one of the values InternetAddress.ANY_IP_V4 or InternetAddress.ANY_IP_V6 to bind to all interfaces or the IP address of a specific interface.
If an IP version 6 (IPv6) address is used, both IP version 6 (IPv6) and version 4 (IPv4) connections will be accepted. To restrict this to version 6 (IPv6) only, use v6Only to set version 6 only.
If port has the value 0
an ephemeral port will be chosen by the system. The actual port used can be retrieved using the port getter.
The optional argument backlog can be used to specify the listen backlog for the underlying OS listen setup. If backlog has the value of 0
(the default) a reasonable value will be chosen by the system.
Closes the socket.
A high-level class for communicating over a TCP socket. The Socket exposes both a Stream and a IOSink interface, making it ideal for using together with other Streams.
Returns the InternetAddress used to connect this socket.
Returns the port used by this socket.
Returns the remote host connected to by this socket.
Returns the remote port connected to by this socket.
Creats a new socket connection to the host and port and returns a Future that will complete with either a Socket once connected or an error if the host-lookup or connection failed.
host can either be a String or an InternetAddress. If host is a String, connect will perform a InternetAddress.lookup and use the first value in the list.
Destroy the socket in both directions. Calling destroy will make the send a close event on the stream and will no longer react on data being piped to it.
Call close(inherited from IOSink) to only close the Socket for sending data.
Use setOption to customize the RawSocket. See SocketOption for available options.
Returns true if the option was set successfully, false otherwise.
The SocketDirection is used as a parameter to Socket.close and RawSocket.close to close a socket in the specified direction(s).
Returns a string representation of this object.
The SocketOption is used as a parameter to Socket.setOption and RawSocket.setOption to set customize the behaviour of the underlying socket.
Enable or disable no-delay on the socket. If TCP_NODELAY is enabled, the socket will not buffer data internally, but instead write each data chunk as an invidual TCP packet.
TCP_NODELAY is disabled by default.
Returns a string representation of this object.
Stream transformer that can decode a stream of bytes into a stream of strings using encoding.
Invalid or forbidden byte-sequences will not produce errors, but will instead insert replacementChar in the decoded strings.
Create a new StringDecoder with an optional encoding and replacementChar.
Stream transformer that can encode a stream of strings info a stream of bytes using encoding.
Strings that cannot be represented in the given encoding will result in an error and a close event on the stream.
Create a new StringDecoder with an optional encoding and replacementChar.
A client or server web socket connection. The stream exposes the messages received. A text message will be of type String
and a binary message will be of type List<int>
.
Possible states of the connection.
The close code set when the web socket connection is closed. If there is no close code available this property will be null
The close reason set when the web socket connection is closed. If there is no close reason available this property will be null
The extensions property is initially the empty string. After the web socket connection is established this string reflects the extensions used by the server.
The protocol property is initially the empty string. After the web socket connection is established the value is the subprotocol selected by the server. If no subprotocol is negotiated the value will remain null
.
Returns the current state of the connection.
Sends data on the web socket connection. The data in data must be either a String
, or a List<int>
holding bytes.
Sends data from a stream on web socket connection. Each data event from stream will be send as a single WebSocket frame. The data from stream must be either String
s, or List<int>
s holding bytes.
Closes the web socket connection. Set the optional code and reason arguments to send close information to the remote peer. If they are omitted, the peer will see WebSocketStatus.NO_STATUS_RECEIVED code with no reason.
Create a new web socket connection. The URL supplied in url must use the scheme ws
or wss
. The protocols argument is either a String
or List<String>
specifying the subprotocols the client is willing to speak.
Returns a string representation of this object.
Web socket status codes used when closing a web socket connection.
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.
To upgrade a single HttpRequest use the static upgrade() method.
HttpServer server; server.listen((request) { if (...) { WebSocketTransformer.upgrade(request).then((websocket) { ... }); } else { // Do normal HTTP request processing. } });To transform a stream of HttpRequest events as it implements a stream transformer that transforms a stream of HttpRequest into a stream of WebSockets by upgrading each HttpRequest from the HTTP or HTTPS server, to the WebSocket protocol.
server.transform(new WebSocketTransformer()).listen((webSocket) => ...);This transformer strives to implement web sockets as specified by RFC6455.
Checks whether the request is a valid WebSocket upgrade request.
Upgrades a HttpRequest to a WebSocket connection. If the request is not a valid web socket upgrade request a HTTP response with status code 500 will be returned. Otherwise the returned future will complete with the WebSocket when the upgrade pocess is complete.
X509Certificate represents an SSL certificate, with accessors to get the fields of the certificate.
ZLibDeflater class used to deflate a stream of bytes, using zlib.
ZLibInflater class used to inflate a stream of bytes, using zlib.


Let's use the video sensor plugin to animate some characters.
1) Add the video sensor puglin and a character sprite to interact with.
2) When the movement near the character is more than 20, have the character respond in some way (playing a sound, applying an effect, changing costume, etc.)
3) Add as many characters as you want and make them respond in different ways. Maybe some react to more movement than others.