A set of error constructors that are raised by Deno APIs.
A controller object that allows you to abort one or more DOM requests as and when desired.
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
The Deno abstraction for reading and writing files.
An event which takes place in the DOM.
EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
Provides information about files and allows JavaScript in a web page to access their content.
The location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Accessible via globalThis.location
.
The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties.
The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.
Encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the .mark()
method) at an explicit point in an application.
PerformanceMark
is an abstract interface for PerformanceEntry
objects with an entryType of "mark"
. Entries of this type are created by calling performance.mark()
to add a named DOMHighResTimeStamp
(the mark) to the performance timeline.
PerformanceMeasure
is an abstract interface for PerformanceEntry
objects with an entryType of "measure"
. Entries of this type are created by calling performance.measure()
to add a named DOMHighResTimeStamp
(the measure) between two marks to the performance timeline.
Events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an , , , or ).
This Fetch API interface represents a resource request.
This Fetch API interface represents the response to a request.
The URL interface represents an object providing static methods used for creating object URLs.
The URLPattern API provides a web platform primitive for matching URLs based on a convenient pattern syntax.
The syntax is based on path-to-regexp. Wildcards, named capture groups, regular groups, and group modifiers are all supported.
// Specify the pattern as structured data.
const pattern = new URLPattern({ pathname: "/users/:user" });
const match = pattern.exec("/users/joe");
console.log(match.pathname.groups.user); // joe
// Specify a fully qualified string pattern.
const pattern = new URLPattern("https://example.com/books/:id");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://deno.land/books/123")); // false
// Specify a relative string pattern with a base URL.
const pattern = new URLPattern("/:article", "https://blog.example.com");
console.log(pattern.test("https://blog.example.com/article")); // true
console.log(pattern.test("https://blog.example.com/article/123")); // false
The WebAssembly.CompileError
object indicates an error during WebAssembly decoding or validation.
A WebAssembly.Global
object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module
instances. This allows dynamic linking of multiple modules.
A WebAssembly.Instance
object is a stateful, executable instance of a WebAssembly.Module
. Instance objects contain all the Exported WebAssembly functions that allow calling into WebAssembly code from JavaScript.
The WebAssembly.LinkError
object indicates an error during module instantiation (besides traps from the start function).
The WebAssembly.Memory
object is a resizable ArrayBuffer
or SharedArrayBuffer
that holds the raw bytes of memory accessed by a WebAssembly Instance.
A memory created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly.
A WebAssembly.Module
object contains stateless WebAssembly code that has already been compiled by the browser — this can be efficiently shared with Workers, and instantiated multiple times.
The WebAssembly.RuntimeError
object is the error type that is thrown whenever WebAssembly specifies a trap.
The WebAssembly.Table()
object is a JavaScript wrapper object — an array-like structure representing a WebAssembly Table, which stores function references. A table created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly.
Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
Returns the script arguments to the program. If for example we run a program:
deno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd
Then Deno.args
will contain:
[ "/etc/passwd" ]
Build related information.
A symbol which can be used as a key for a custom method which will be called when Deno.inspect()
is called, or when the object is logged to the console.
The URL of the entrypoint module entered from the command-line.
Reflects the NO_COLOR
environment variable at program start.
Deno's permission management API.
The current process id of the runtime.
The pid of the current process's parent.
A handle for stderr
.
A handle for stdin
.
A handle for stdout
.
Version related information.
Registers an event listener in the global scope, which will be called synchronously whenever the event type
is dispatched.
addEventListener('unload', () => { console.log('All finished!'); });
...
dispatchEvent(new Event('unload'));
Shows the given message and waits for the enter key pressed. If the stdin is not interactive, it does nothing.
Decodes a string of data which has been encoded using base-64 encoding.
console.log(atob("aGVsbG8gd29ybGQ=")); // outputs 'hello world'
Creates a base-64 ASCII encoded string from the input string.
console.log(btoa("hello world")); // outputs "aGVsbG8gd29ybGQ="
Cancels a timed, repeating action which was previously started by a call to setInterval()
const id = setInterval(() => {console.log('hello');}, 500);
// ...
clearInterval(id);
Cancels a scheduled action initiated by setTimeout()
const id = setTimeout(() => {console.log('hello');}, 500);
// ...
clearTimeout(id);
Shows the given message and waits for the answer. Returns the user's answer as boolean. Only y
and Y
are considered as true. If the stdin is not interactive, it returns false.
Change the current working directory to the specified path.
Deno.chdir("/home/userA");
Deno.chdir("../userB");
Deno.chdir("C:\\Program Files (x86)\\Java");
Throws Deno.errors.NotFound
if directory not found. Throws Deno.errors.PermissionDenied
if the user does not have access rights
Requires --allow-read.
Changes the permission of a specific file/directory of specified path. Ignores the process's umask.
await Deno.chmod("/path/to/file", 0o666);
The mode is a sequence of 3 octal numbers. The first/left-most number specifies the permissions for the owner. The second number specifies the permissions for the group. The last/right-most number specifies the permissions for others. For example, with a mode of 0o764, the owner (7) can read/write/execute, the group (6) can read/write and everyone else (4) can read only.
Number | Description |
---|---|
7 | read, write, and execute |
6 | read and write |
5 | read and execute |
4 | read only |
3 | write and execute |
2 | write only |
1 | execute only |
0 | no permission |
NOTE: This API currently throws on Windows
Requires allow-write
permission.
Synchronously changes the permission of a specific file/directory of specified path. Ignores the process's umask.
Deno.chmodSync("/path/to/file", 0o666);
For a full description, see chmod
NOTE: This API currently throws on Windows
Requires allow-write
permission.
Change owner of a regular file or directory. This functionality is not available on Windows.
await Deno.chown("myFile.txt", 1000, 1002);
Requires allow-write
permission.
Throws Error (not implemented) if executed on Windows
Synchronously change owner of a regular file or directory. This functionality is not available on Windows.
Deno.chownSync("myFile.txt", 1000, 1002);
Requires allow-write
permission.
Throws Error (not implemented) if executed on Windows
Close the given resource ID (rid) which has been previously opened, such as via opening or creating a file. Closing a file when you are finished with it is important to avoid leaking resources.
const file = await Deno.open("my_file.txt");
// do work with "file" object
Deno.close(file.rid);
Connects to the hostname (default is "127.0.0.1") and port on the named transport (default is "tcp"), and resolves to the connection (Conn
).
const conn1 = await Deno.connect({ port: 80 });
const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
Requires allow-net
permission for "tcp".
Establishes a secure connection over TLS (transport layer security) using an optional cert file, hostname (default is "127.0.0.1") and port. The cert file is optional and if not included Mozilla's root certificates will be used (see also https://github.com/ctz/webpki-roots for specifics)
const caCert = await Deno.readTextFile("./certs/my_custom_root_CA.pem");
const conn1 = await Deno.connectTls({ port: 80 });
const conn2 = await Deno.connectTls({ caCerts: [caCert], hostname: "192.0.2.1", port: 80 });
const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 });
const conn4 = await Deno.connectTls({ caCerts: [caCert], hostname: "golang.org", port: 80});
Requires allow-net
permission.
Copies from src
to dst
until either EOF (null
) is read from src
or an error occurs. It resolves to the number of bytes copied or rejects with the first error encountered while copying.
const source = await Deno.open("my_file.txt");
const bytesCopied1 = await Deno.copy(source, Deno.stdout);
const destination = await Deno.create("my_file_2.txt");
const bytesCopied2 = await Deno.copy(source, destination);
Copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting. Fails if target path is a directory or is unwritable.
await Deno.copyFile("from.txt", "to.txt");
Requires allow-read
permission on fromPath. Requires allow-write
permission on toPath.
Synchronously copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting. Fails if target path is a directory or is unwritable.
Deno.copyFileSync("from.txt", "to.txt");
Requires allow-read
permission on fromPath. Requires allow-write
permission on toPath.
Creates a file if none exists or truncates an existing file and resolves to an instance of Deno.File
.
const file = await Deno.create("/foo/bar.txt");
Requires allow-read
and allow-write
permissions.
Creates a file if none exists or truncates an existing file and returns an instance of Deno.File
.
const file = Deno.createSync("/foo/bar.txt");
Requires allow-read
and allow-write
permissions.
Return a string representing the current working directory.
If the current directory can be reached via multiple paths (due to symbolic links), cwd()
may return any one of them.
const currentWorkingDirectory = Deno.cwd();
Throws Deno.errors.NotFound
if directory not available.
Requires --allow-read
Returns the path to the current deno executable.
console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno"
Requires allow-read
permission.
Exit the Deno process with optional exit code. If no exit code is supplied then Deno will exit with return code of 0.
Deno.exit(5);
Flushes any pending data operations of the given file stream to disk.
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.write(file.rid, new TextEncoder().encode("Hello World"));
await Deno.fdatasync(file.rid);
console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // Hello World
Returns a Deno.FileInfo
for the given file stream.
import { assert } from "https://deno.land/std/testing/asserts.ts";
const file = await Deno.open("file.txt", { read: true });
const fileInfo = await Deno.fstat(file.rid);
assert(fileInfo.isFile);
Synchronously returns a Deno.FileInfo
for the given file stream.
import { assert } from "https://deno.land/std/testing/asserts.ts";
const file = Deno.openSync("file.txt", { read: true });
const fileInfo = Deno.fstatSync(file.rid);
assert(fileInfo.isFile);
Flushes any pending data and metadata operations of the given file stream to disk.
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.write(file.rid, new TextEncoder().encode("Hello World"));
await Deno.ftruncate(file.rid, 1);
await Deno.fsync(file.rid);
console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // H
Synchronously flushes any pending data and metadata operations of the given file stream to disk.
const file = Deno.openSync("my_file.txt", { read: true, write: true, create: true });
Deno.writeSync(file.rid, new TextEncoder().encode("Hello World"));
Deno.ftruncateSync(file.rid, 1);
Deno.fsyncSync(file.rid);
console.log(new TextDecoder().decode(Deno.readFileSync("my_file.txt"))); // H
Truncates or extends the specified file stream, to reach the specified len
.
If len
is not specified then the entire file contents are truncated as if len was set to 0.
If the file previously was larger than this new length, the extra data is lost.
If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
// truncate the entire file
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.ftruncate(file.rid);
// truncate part of the file
const file = await Deno.open("my_file.txt", { read: true, write: true, create: true });
await Deno.write(file.rid, new TextEncoder().encode("Hello World"));
await Deno.ftruncate(file.rid, 7);
const data = new Uint8Array(32);
await Deno.read(file.rid, data);
console.log(new TextDecoder().decode(data)); // Hello W
Synchronously truncates or extends the specified file stream, to reach the specified len
.
If len
is not specified then the entire file contents are truncated as if len was set to 0.
if the file previously was larger than this new length, the extra data is lost.
if the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
// truncate the entire file
const file = Deno.openSync("my_file.txt", { read: true, write: true, truncate: true, create: true });
Deno.ftruncateSync(file.rid);
// truncate part of the file
const file = Deno.openSync("my_file.txt", { read: true, write: true, create: true });
Deno.writeSync(file.rid, new TextEncoder().encode("Hello World"));
Deno.ftruncateSync(file.rid, 7);
Deno.seekSync(file.rid, 0, Deno.SeekMode.Start);
const data = new Uint8Array(32);
Deno.readSync(file.rid, data);
console.log(new TextDecoder().decode(data)); // Hello W
Converts the input into a string that has the same format as printed by console.log()
.
const obj = {
a: 10,
b: "hello",
};
const objAsString = Deno.inspect(obj); // { a: 10, b: "hello" }
console.log(obj); // prints same value as objAsString, e.g. { a: 10, b: "hello" }
You can also register custom inspect functions, via the symbol Symbol.for("Deno.customInspect")
, on objects, to control and customize the output.
class A {
x = 10;
y = "hello";
[Symbol.for("Deno.customInspect")](): string {
return "x=" + this.x + ", y=" + this.y;
}
}
const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello"
console.log(inStringFormat); // prints "x=10, y=hello"
Finally, you can also specify the depth to which it will format.
Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } }
Check if a given resource id (rid
) is a TTY.
// This example is system and context specific
const nonTTYRid = Deno.openSync("my_file.txt").rid;
const ttyRid = Deno.openSync("/dev/tty6").rid;
console.log(Deno.isatty(nonTTYRid)); // false
console.log(Deno.isatty(ttyRid)); // true
Deno.close(nonTTYRid);
Deno.close(ttyRid);
Turns a Reader, r
, into an async iterator.
let f = await Deno.open("/etc/passwd");
for await (const chunk of Deno.iter(f)) {
console.log(chunk);
}
f.close();
Second argument can be used to tune size of a buffer. Default size of the buffer is 32kB.
let f = await Deno.open("/etc/passwd");
const iter = Deno.iter(f, {
bufSize: 1024 * 1024
});
for await (const chunk of iter) {
console.log(chunk);
}
f.close();
Iterator uses an internal buffer of fixed size for efficiency; it returns a view on that buffer on each iteration. It is therefore caller's responsibility to copy contents of the buffer if needed; otherwise the next iteration will overwrite contents of previously returned chunk.
Turns a ReaderSync, r
, into an iterator.
let f = Deno.openSync("/etc/passwd");
for (const chunk of Deno.iterSync(f)) {
console.log(chunk);
}
f.close();
Second argument can be used to tune size of a buffer. Default size of the buffer is 32kB.
let f = await Deno.open("/etc/passwd");
const iter = Deno.iterSync(f, {
bufSize: 1024 * 1024
});
for (const chunk of iter) {
console.log(chunk);
}
f.close();
Iterator uses an internal buffer of fixed size for efficiency; it returns a view on that buffer on each iteration. It is therefore caller's responsibility to copy contents of the buffer if needed; otherwise the next iteration will overwrite contents of previously returned chunk.
Send a signal to process under given pid
.
If pid
is negative, the signal will be sent to the process group identified by pid
.
const p = Deno.run({
cmd: ["sleep", "10000"]
});
Deno.kill(p.pid, "SIGINT");
Requires allow-run
permission.
Creates newpath
as a hard link to oldpath
.
await Deno.link("old/name", "new/name");
Requires allow-read
and allow-write
permissions.
Synchronously creates newpath
as a hard link to oldpath
.
Deno.linkSync("old/name", "new/name");
Requires allow-read
and allow-write
permissions.
Listen announces on the local transport address.
const listener1 = Deno.listen({ port: 80 })
const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });
Requires allow-net
permission.
Listen announces on the local transport address over TLS (transport layer security).
const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" });
Requires allow-net
permission.
Resolves to a Deno.FileInfo
for the specified path
. If path
is a symlink, information for the symlink will be returned instead of what it points to.
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = await Deno.lstat("hello.txt");
assert(fileInfo.isFile);
Requires allow-read
permission.
Synchronously returns a Deno.FileInfo
for the specified path
. If path
is a symlink, information for the symlink will be returned instead of what it points to..
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = Deno.lstatSync("hello.txt");
assert(fileInfo.isFile);
Requires allow-read
permission.
Creates a new temporary directory in the default directory for temporary files, unless dir
is specified. Other optional options include prefixing and suffixing the directory name with prefix
and suffix
respectively.
This call resolves to the full path to the newly created directory.
Multiple programs calling this function simultaneously will create different directories. It is the caller's responsibility to remove the directory when no longer needed.
const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76
const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
Requires allow-write
permission.
Synchronously creates a new temporary directory in the default directory for temporary files, unless dir
is specified. Other optional options include prefixing and suffixing the directory name with prefix
and suffix
respectively.
The full path to the newly created directory is returned.
Multiple programs calling this function simultaneously will create different directories. It is the caller's responsibility to remove the directory when no longer needed.
const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76
const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
Requires allow-write
permission.
Creates a new temporary file in the default directory for temporary files, unless dir
is specified. Other optional options include prefixing and suffixing the directory name with prefix
and suffix
respectively.
This call resolves to the full path to the newly created file.
Multiple programs calling this function simultaneously will create different files. It is the caller's responsibility to remove the file when no longer needed.
const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2
const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
Requires allow-write
permission.
Synchronously creates a new temporary file in the default directory for temporary files, unless dir
is specified. Other optional options include prefixing and suffixing the directory name with prefix
and suffix
respectively.
The full path to the newly created file is returned.
Multiple programs calling this function simultaneously will create different files. It is the caller's responsibility to remove the file when no longer needed.
const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
Requires allow-write
permission.
Returns an object describing the memory usage of the Deno process measured in bytes.
Receive metrics from the privileged side of Deno. This is primarily used in the development of Deno. 'Ops', also called 'bindings', are the go-between between Deno JavaScript and Deno Rust.
> console.table(Deno.metrics())
┌─────────────────────────┬────────┐
│ (index) │ Values │
├─────────────────────────┼────────┤
│ opsDispatched │ 3 │
│ opsDispatchedSync │ 2 │
│ opsDispatchedAsync │ 1 │
│ opsDispatchedAsyncUnref │ 0 │
│ opsCompleted │ 3 │
│ opsCompletedSync │ 2 │
│ opsCompletedAsync │ 1 │
│ opsCompletedAsyncUnref │ 0 │
│ bytesSentControl │ 73 │
│ bytesSentData │ 0 │
│ bytesReceived │ 375 │
└─────────────────────────┴────────┘
Creates a new directory with the specified path.
await Deno.mkdir("new_dir");
await Deno.mkdir("nested/directories", { recursive: true });
await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
Defaults to throwing error if the directory already exists.
Requires allow-write
permission.
Synchronously creates a new directory with the specified path.
Deno.mkdirSync("new_dir");
Deno.mkdirSync("nested/directories", { recursive: true });
Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });
Defaults to throwing error if the directory already exists.
Requires allow-write
permission.
Open a file and resolve to an instance of Deno.File
. The file does not need to previously exist if using the create
or createNew
open options. It is the callers responsibility to close the file when finished with it.
const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
// Do work with file
Deno.close(file.rid);
Requires allow-read
and/or allow-write
permissions depending on options.
Synchronously open a file and return an instance of Deno.File
. The file does not need to previously exist if using the create
or createNew
open options. It is the callers responsibility to close the file when finished with it.
const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
// Do work with file
Deno.close(file.rid);
Requires allow-read
and/or allow-write
permissions depending on options.
Read from a resource ID (rid
) into an array buffer (buffer
).
Resolves to either the number of bytes read during the operation or EOF (null
) if there was nothing more to read.
It is possible for a read to successfully return with 0
bytes. This does not indicate EOF.
This function is one of the lowest level APIs and most users should not work with this directly, but rather use Deno.readAll() instead.
It is not guaranteed that the full buffer will be read in a single call.
// if "/foo/bar.txt" contains the text "hello world":
const file = await Deno.open("/foo/bar.txt");
const buf = new Uint8Array(100);
const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
const text = new TextDecoder().decode(buf); // "hello world"
Deno.close(file.rid);
Read Reader r
until EOF (null
) and resolve to the content as Uint8Array`.
// Example from stdin
const stdinContent = await Deno.readAll(Deno.stdin);
// Example from file
const file = await Deno.open("my_file.txt", {read: true});
const myFileContent = await Deno.readAll(file);
Deno.close(file.rid);
// Example from buffer
const myData = new Uint8Array(100);
// ... fill myData array with data
const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
const bufferContent = await Deno.readAll(reader);
Synchronously reads Reader r
until EOF (null
) and returns the content as Uint8Array
.
// Example from stdin
const stdinContent = Deno.readAllSync(Deno.stdin);
// Example from file
const file = Deno.openSync("my_file.txt", {read: true});
const myFileContent = Deno.readAllSync(file);
Deno.close(file.rid);
// Example from buffer
const myData = new Uint8Array(100);
// ... fill myData array with data
const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
const bufferContent = Deno.readAllSync(reader);
Reads the directory given by path
and returns an async iterable of Deno.DirEntry
.
for await (const dirEntry of Deno.readDir("/")) {
console.log(dirEntry.name);
}
Throws error if path
is not a directory.
Requires allow-read
permission.
Synchronously reads the directory given by path
and returns an iterable of Deno.DirEntry
.
for (const dirEntry of Deno.readDirSync("/")) {
console.log(dirEntry.name);
}
Throws error if path
is not a directory.
Requires allow-read
permission.
Reads and resolves to the entire contents of a file as an array of bytes. TextDecoder
can be used to transform the bytes to string if required. Reading a directory returns an empty data array.
const decoder = new TextDecoder("utf-8");
const data = await Deno.readFile("hello.txt");
console.log(decoder.decode(data));
Requires allow-read
permission.
Synchronously reads and returns the entire contents of a file as an array of bytes. TextDecoder
can be used to transform the bytes to string if required. Reading a directory returns an empty data array.
const decoder = new TextDecoder("utf-8");
const data = Deno.readFileSync("hello.txt");
console.log(decoder.decode(data));
Requires allow-read
permission.
Resolves to the full path destination of the named symbolic link.
await Deno.symlink("./test.txt", "./test_link.txt");
const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt
Throws TypeError if called with a hard link
Requires allow-read
permission.
Returns the full path destination of the named symbolic link.
Deno.symlinkSync("./test.txt", "./test_link.txt");
const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt
Throws TypeError if called with a hard link
Requires allow-read
permission.
Synchronously read from a resource ID (rid
) into an array buffer (buffer
).
Returns either the number of bytes read during the operation or EOF (null
) if there was nothing more to read.
It is possible for a read to successfully return with 0
bytes. This does not indicate EOF.
This function is one of the lowest level APIs and most users should not work with this directly, but rather use Deno.readAllSync() instead.
It is not guaranteed that the full buffer will be read in a single call.
// if "/foo/bar.txt" contains the text "hello world":
const file = Deno.openSync("/foo/bar.txt");
const buf = new Uint8Array(100);
const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
const text = new TextDecoder().decode(buf); // "hello world"
Deno.close(file.rid);
Asynchronously reads and returns the entire contents of a file as utf8 encoded string. Reading a directory throws an error.
const data = await Deno.readTextFile("hello.txt");
console.log(data);
Requires allow-read
permission.
Synchronously reads and returns the entire contents of a file as utf8 encoded string. Reading a directory throws an error.
const data = Deno.readTextFileSync("hello.txt");
console.log(data);
Requires allow-read
permission.
Resolves to the absolute normalized path, with symbolic links resolved.
// e.g. given /home/alice/file.txt and current directory /home/alice
await Deno.symlink("file.txt", "symlink_file.txt");
const realPath = await Deno.realPath("./file.txt");
const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
console.log(realPath); // outputs "/home/alice/file.txt"
console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
Requires allow-read
permission for the target path. Also requires allow-read
permission for the CWD if the target path is relative.
Returns absolute normalized path, with symbolic links resolved.
// e.g. given /home/alice/file.txt and current directory /home/alice
Deno.symlinkSync("file.txt", "symlink_file.txt");
const realPath = Deno.realPathSync("./file.txt");
const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
console.log(realPath); // outputs "/home/alice/file.txt"
console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
Requires allow-read
permission for the target path. Also requires allow-read
permission for the CWD if the target path is relative.
Removes the named file or directory.
await Deno.remove("/path/to/empty_dir/or/file");
await Deno.remove("/path/to/populated_dir/or/file", { recursive: true });
Throws error if permission denied, path not found, or path is a non-empty directory and the recursive
option isn't set to true
.
Requires allow-write
permission.
Synchronously removes the named file or directory.
Deno.removeSync("/path/to/empty_dir/or/file");
Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });
Throws error if permission denied, path not found, or path is a non-empty directory and the recursive
option isn't set to true
.
Requires allow-write
permission.
Renames (moves) oldpath
to newpath
. Paths may be files or directories. If newpath
already exists and is not a directory, rename()
replaces it. OS-specific restrictions may apply when oldpath
and newpath
are in different directories.
await Deno.rename("old/path", "new/path");
On Unix, this operation does not follow symlinks at either path.
It varies between platforms when the operation throws errors, and if so what they are. It's always an error to rename anything to a non-empty directory.
Requires allow-read
and allow-write
permission.
Synchronously renames (moves) oldpath
to newpath
. Paths may be files or directories. If newpath
already exists and is not a directory, renameSync()
replaces it. OS-specific restrictions may apply when oldpath
and newpath
are in different directories.
Deno.renameSync("old/path", "new/path");
On Unix, this operation does not follow symlinks at either path.
It varies between platforms when the operation throws errors, and if so what they are. It's always an error to rename anything to a non-empty directory.
Requires allow-read
and allow-write
permissions.
Returns a map of open resource ids (rid) along with their string representations. This is an internal API and as such resource representation has any
type; that means it can change any time.
console.log(Deno.resources());
// { 0: "stdin", 1: "stdout", 2: "stderr" }
Deno.openSync('../test.file');
console.log(Deno.resources());
// { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }
Spawns new subprocess. RunOptions must contain at a minimum the opt.cmd
, an array of program arguments, the first of which is the binary.
const p = Deno.run({
cmd: ["echo", "hello"],
});
Subprocess uses same working directory as parent process unless opt.cwd
is specified.
Environmental variables from parent process can be cleared using opt.clearEnv
. Doesn't guarantee that only opt.env
variables are present, as the OS may set environmental variables for processes.
Environmental variables for subprocess can be specified using opt.env
mapping.
opt.uid
sets the child process’s user ID. This translates to a setuid call in the child process. Failure in the setuid call will cause the spawn to fail.
opt.gid
is similar to opt.uid
, but sets the group ID of the child process. This has the same semantics as the uid field.
By default subprocess inherits stdio of parent process. To change that opt.stdout
, opt.stderr
and opt.stdin
can be specified independently - they can be set to either an rid of open file or set to "inherit" "piped" or "null":
"inherit"
The default if unspecified. The child inherits from the corresponding parent descriptor.
"piped"
A new pipe should be arranged to connect the parent and child sub-processes.
"null"
This stream will be ignored. This is the equivalent of attaching the stream to /dev/null
.
Details of the spawned process are returned.
Requires allow-run
permission.
Seek a resource ID (rid
) to the given offset
under mode given by whence
. The call resolves to the new position within the resource (bytes from the start).
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
// advance cursor 6 bytes
const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start);
console.log(cursorPosition); // 6
const buf = new Uint8Array(100);
await file.read(buf);
console.log(new TextDecoder().decode(buf)); // "world"
The seek modes work as follows:
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
// Seek 6 bytes from the start of the file
console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
Synchronously seek a resource ID (rid
) to the given offset
under mode given by whence
. The new position within the resource (bytes from the start) is returned.
const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
// advance cursor 6 bytes
const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start);
console.log(cursorPosition); // 6
const buf = new Uint8Array(100);
file.readSync(buf);
console.log(new TextDecoder().decode(buf)); // "world"
The seek modes work as follows:
// Given file.rid pointing to file with "Hello world", which is 11 bytes long:
const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
// Seek 6 bytes from the start of the file
console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
Services HTTP requests given a TCP or TLS socket.
const conn = await Deno.listen({ port: 80 });
const httpConn = Deno.serveHttp(await conn.accept());
const e = await httpConn.nextRequest();
if (e) {
e.respondWith(new Response("Hello World"));
}
If httpConn.nextRequest()
encounters an error or returns null
then the underlying HttpConn resource is closed automatically.
Alternatively, you can also use the Async Iterator approach:
async function handleHttp(conn: Deno.Conn) {
for await (const e of Deno.serveHttp(conn)) {
e.respondWith(new Response("Hello World"));
}
}
for await (const conn of Deno.listen({ port: 80 })) {
handleHttp(conn);
}
Shutdown socket send operations.
Matches behavior of POSIX shutdown(3).
const listener = Deno.listen({ port: 80 });
const conn = await listener.accept();
Deno.shutdown(conn.rid);
Start TLS handshake from an existing connection using an optional list of CA certificates, and hostname (default is "127.0.0.1"). Specifying CA certs is optional. By default the configured root certificates are used. Using this function requires that the other end of the connection is prepared for a TLS handshake.
const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
const caCert = await Deno.readTextFile("./certs/my_custom_root_CA.pem");
const tlsConn = await Deno.startTls(conn, { caCerts: [caCert], hostname: "localhost" });
Requires allow-net
permission.
Resolves to a Deno.FileInfo
for the specified path
. Will always follow symlinks.
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = await Deno.stat("hello.txt");
assert(fileInfo.isFile);
Requires allow-read
permission.
Synchronously returns a Deno.FileInfo
for the specified path
. Will always follow symlinks.
import { assert } from "https://deno.land/std/testing/asserts.ts";
const fileInfo = Deno.statSync("hello.txt");
assert(fileInfo.isFile);
Requires allow-read
permission.
Creates newpath
as a symbolic link to oldpath
.
The options.type parameter can be set to file
or dir
. This argument is only available on Windows and ignored on other platforms.
await Deno.symlink("old/name", "new/name");
Requires full allow-read
and allow-write
permissions.
Creates newpath
as a symbolic link to oldpath
.
The options.type parameter can be set to file
or dir
. This argument is only available on Windows and ignored on other platforms.
Deno.symlinkSync("old/name", "new/name");
Requires full allow-read
and allow-write
permissions.
Register a test which will be run when deno test
is used on the command line and the containing module looks like a test module. fn
can be async if required.
import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
Deno.test({
name: "example test",
fn(): void {
assertEquals("world", "world");
},
});
Deno.test({
name: "example ignored test",
ignore: Deno.build.os === "windows",
fn(): void {
// This test is ignored only on Windows machines
},
});
Deno.test({
name: "example async test",
async fn() {
const decoder = new TextDecoder("utf-8");
const data = await Deno.readFile("hello_world.txt");
assertEquals(decoder.decode(data), "Hello world");
}
});
Truncates or extends the specified file, to reach the specified len
. If len
is not specified then the entire file contents are truncated.
// truncate the entire file
await Deno.truncate("my_file.txt");
// truncate part of the file
const file = await Deno.makeTempFile();
await Deno.writeFile(file, new TextEncoder().encode("Hello World"));
await Deno.truncate(file, 7);
const data = await Deno.readFile(file);
console.log(new TextDecoder().decode(data)); // "Hello W"
Requires allow-write
permission.
Synchronously truncates or extends the specified file, to reach the specified len
. If len
is not specified then the entire file contents are truncated.
// truncate the entire file
Deno.truncateSync("my_file.txt");
// truncate part of the file
const file = Deno.makeTempFileSync();
Deno.writeFileSync(file, new TextEncoder().encode("Hello World"));
Deno.truncateSync(file, 7);
const data = Deno.readFileSync(file);
console.log(new TextDecoder().decode(data));
Requires allow-write
permission.
Used to upgrade an incoming HTTP request to a WebSocket.
Given a request, returns a pair of WebSocket and Response. The original request must be responded to with the returned response for the websocket upgrade to be successful.
const conn = await Deno.listen({ port: 80 });
const httpConn = Deno.serveHttp(await conn.accept());
const e = await httpConn.nextRequest();
if (e) {
const { socket, response } = Deno.upgradeWebSocket(e.request);
socket.onopen = () => {
socket.send("Hello World!");
};
socket.onmessage = (e) => {
console.log(e.data);
socket.close();
};
socket.onclose = () => console.log("WebSocket has been closed.");
socket.onerror = (e) => console.error("WebSocket error:", e);
e.respondWith(response);
}
If the request body is disturbed (read from) before the upgrade is completed, upgrading fails.
This operation does not yet consume the request or open the websocket. This only happens once the returned response has been passed to respondWith
.
Watch for file system events against one or more paths
, which can be files or directories. These paths must exist already. One user action (e.g. touch test.file
) can generate multiple file system events. Likewise, one user action can result in multiple file paths in one event (e.g. mv old_name.txt new_name.txt
). Recursive option is true
by default and, for directories, will watch the specified directory and all sub directories. Note that the exact ordering of the events can vary between operating systems.
const watcher = Deno.watchFs("/");
for await (const event of watcher) {
console.log(">>>> event", event);
// { kind: "create", paths: [ "/foo.txt" ] }
}
Requires allow-read
permission.
Call watcher.close()
to stop watching.
const watcher = Deno.watchFs("/");
setTimeout(() => {
watcher.close();
}, 5000);
for await (const event of watcher) {
console.log(">>>> event", event);
}
Write to the resource ID (rid
) the contents of the array buffer (data
).
Resolves to the number of bytes written. This function is one of the lowest level APIs and most users should not work with this directly, but rather use Deno.writeAll() instead.
It is not guaranteed that the full buffer will be written in a single call.
const encoder = new TextEncoder();
const data = encoder.encode("Hello world");
const file = await Deno.open("/foo/bar.txt", { write: true });
const bytesWritten = await Deno.write(file.rid, data); // 11
Deno.close(file.rid);
Write all the content of the array buffer (arr
) to the writer (w
).
// Example writing to stdout
const contentBytes = new TextEncoder().encode("Hello World");
await Deno.writeAll(Deno.stdout, contentBytes);
// Example writing to file
const contentBytes = new TextEncoder().encode("Hello World");
const file = await Deno.open('test.file', {write: true});
await Deno.writeAll(file, contentBytes);
Deno.close(file.rid);
// Example writing to buffer
const contentBytes = new TextEncoder().encode("Hello World");
const writer = new Deno.Buffer();
await Deno.writeAll(writer, contentBytes);
console.log(writer.bytes().length); // 11
Synchronously write all the content of the array buffer (arr
) to the writer (w
).
// Example writing to stdout
const contentBytes = new TextEncoder().encode("Hello World");
Deno.writeAllSync(Deno.stdout, contentBytes);
// Example writing to file
const contentBytes = new TextEncoder().encode("Hello World");
const file = Deno.openSync('test.file', {write: true});
Deno.writeAllSync(file, contentBytes);
Deno.close(file.rid);
// Example writing to buffer
const contentBytes = new TextEncoder().encode("Hello World");
const writer = new Deno.Buffer();
Deno.writeAllSync(writer, contentBytes);
console.log(writer.bytes().length); // 11
Write data
to the given path
, by default creating a new file if needed, else overwriting.
const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it
await Deno.writeFile("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
await Deno.writeFile("hello3.txt", data, {mode: 0o777}); // set permissions on new file
await Deno.writeFile("hello4.txt", data, {append: true}); // add data to the end of the file
Requires allow-write
permission, and allow-read
if options.create
is false
.
Synchronously write data
to the given path
, by default creating a new file if needed, else overwriting.
const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it
Deno.writeFileSync("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
Deno.writeFileSync("hello3.txt", data, {mode: 0o777}); // set permissions on new file
Deno.writeFileSync("hello4.txt", data, {append: true}); // add data to the end of the file
Requires allow-write
permission, and allow-read
if options.create
is false
.
Synchronously write to the resource ID (rid
) the contents of the array buffer (data
).
Returns the number of bytes written. This function is one of the lowest level APIs and most users should not work with this directly, but rather use Deno.writeAllSync() instead.
It is not guaranteed that the full buffer will be written in a single call.
const encoder = new TextEncoder();
const data = encoder.encode("Hello world");
const file = Deno.openSync("/foo/bar.txt", {write: true});
const bytesWritten = Deno.writeSync(file.rid, data); // 11
Deno.close(file.rid);
Asynchronously write string data
to the given path
, by default creating a new file if needed, else overwriting.
await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
Requires allow-write
permission, and allow-read
if options.create
is false
.
Synchronously write string data
to the given path
, by default creating a new file if needed, else overwriting.
Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
Requires allow-write
permission, and allow-read
if options.create
is false
.
Dispatches an event in the global scope, synchronously invoking any registered event listeners for this event in the appropriate order. Returns false if event is cancelable and at least one of the event handlers which handled this event called Event.preventDefault(). Otherwise it returns true.
dispatchEvent(new Event('unload'));
Fetch a resource from the network. It returns a Promise that resolves to the Response to that request, whether it is successful or not.
const response = await fetch("http://my.json.host/data.json");
console.log(response.status); // e.g. 200
console.log(response.statusText); // e.g. "OK"
const jsonData = await response.json();
Shows the given message and waits for the user's input. Returns the user's input as string. If the default value is given and the user inputs the empty string, then it returns the given default value. If the default value is not given and the user inputs the empty string, it returns null. If the stdin is not interactive, it returns null.
A microtask is a short function which is executed after the function or module which created it exits and only if the JavaScript execution stack is empty, but before returning control to the event loop being used to drive the script's execution environment. This event loop may be either the main event loop or the event loop driving a web worker.
queueMicrotask(() => { console.log('This event loop stack is complete'); });
Remove a previously registered event listener from the global scope
const lstnr = () => { console.log('hello'); };
addEventListener('load', lstnr);
removeEventListener('load', lstnr);
Repeatedly calls a function , with a fixed time delay between each call.
// Outputs 'hello' to the console every 500ms
setInterval(() => { console.log('hello'); }, 500);
Sets a timer which executes a function once after the timer expires. Returns an id which may be used to cancel the timeout.
setTimeout(() => { console.log('hello'); }, 500);
The WebAssembly.compile()
function compiles WebAssembly binary code into a WebAssembly.Module
object. This function is useful if it is necessary to compile a module before it can be instantiated (otherwise, the WebAssembly.instantiate()
function should be used).
The WebAssembly.compileStreaming()
function compiles a WebAssembly.Module
directly from a streamed underlying source. This function is useful if it is necessary to a compile a module before it can be instantiated (otherwise, the WebAssembly.instantiateStreaming()
function should be used).
The WebAssembly.instantiate() function allows you to compile and instantiate WebAssembly code.
This overload takes the WebAssembly binary code, in the form of a typed array or ArrayBuffer, and performs both compilation and instantiation in one step. The returned Promise resolves to both a compiled WebAssembly.Module and its first WebAssembly.Instance.
The WebAssembly.instantiateStreaming()
function compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load wasm code.
The WebAssembly.validate()
function validates a given typed array of WebAssembly binary code, returning whether the bytes form a valid wasm module (true
) or not (false
).
A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.
The CryptoKeyPair dictionary of the Web Crypto API represents a key pair for an asymmetric cryptography algorithm, also known as a public-key algorithm.
A FileInfo describes a file and is returned by stat
, lstat
, statSync
, lstatSync
.
FsWatcher is returned by Deno.watchFs
function when you start watching the file system. You can iterate over this interface to get the file system events, and also you can stop watching the file system by calling .close()
method.
A generic network listener for stream-oriented protocols.
If resolveDns
is called with "MX" record type specified, it will return an array of this interface.
If resolveDns
is called with "SRV" record type specified, it will return an array of this interface.
UNSTABLE: New option, yet to be vetted.
Specialized listener that accepts TLS connections.
Options for writing to a file.
Lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like append() (see Examples). In all methods of this interface, header names are matched by case-insensitive byte sequence.
Deno provides extra properties on import.meta
. These are included here to ensure that these are still available when using the Deno namespace in conjunction with other type libs, like dom
.
Deno supports user timing Level 3 (see: https://w3c.github.io/user-timing) which is not widely supported yet in other runtimes. These types are here so that these features are still available when using the Deno namespace in conjunction with other type libs, like dom
.
This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
This Web Storage API interface provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.
This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto).
URLPatternResult
is the object returned from URLPattern.exec
.
The GlobalDescriptor
describes the options you can pass to new WebAssembly.Global()
.
The MemoryDescriptor
describes the options you can pass to new WebAssembly.Memory()
.
A ModuleExportDescriptor
is the description of a declared export in a WebAssembly.Module
.
A ModuleImportDescriptor
is the description of a declared import in a WebAssembly.Module
.
The TableDescriptor
describes the options you can pass to new WebAssembly.Table()
.
The value returned from WebAssembly.instantiate
.
This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink.
Additional information for FsEvent objects with the "other" kind.
Permission descriptors which define a permission and can be queried, requested, or revoked.
The name of a "powerful feature" which needs permission.
The current status of the permission.
The type of the resource record. Only the listed types are supported currently.
© 2018–2021 the Deno authors
https://doc.deno.land/deno/stable/