W3cubDocs

/Deno

Namespaces

Classes

Enums

Variables

Functions

  • addEventListener

    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'));
    
  • alert

    Shows the given message and waits for the enter key pressed. If the stdin is not interactive, it does nothing.

  • atob

    Decodes a string of data which has been encoded using base-64 encoding.

    console.log(atob("aGVsbG8gd29ybGQ=")); // outputs 'hello world'
    
  • btoa

    Creates a base-64 ASCII encoded string from the input string.

    console.log(btoa("hello world"));  // outputs "aGVsbG8gd29ybGQ="
    
  • clearInterval

    Cancels a timed, repeating action which was previously started by a call to setInterval()

    const id = setInterval(() => {console.log('hello');}, 500);
    // ...
    clearInterval(id);
    
  • clearTimeout

    Cancels a scheduled action initiated by setTimeout()

    const id = setTimeout(() => {console.log('hello');}, 500);
    // ...
    clearTimeout(id);
    
  • confirm

    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.

  • Deno.chdir

    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.

  • Deno.chmod

    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.

  • Deno.chmodSync

    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.

  • Deno.chown

    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

  • Deno.chownSync

    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

  • Deno.close

    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);
    
  • Deno.connect

    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".

  • Deno.connectTls

    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.

  • Deno.copy deprecated

    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);
    
  • Deno.copyFile

    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.

  • Deno.copyFileSync

    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.

  • Deno.create

    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.

  • Deno.createSync

    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.

  • Deno.cwd

    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

  • Deno.execPath

    Returns the path to the current deno executable.

    console.log(Deno.execPath());  // e.g. "/home/alice/.local/bin/deno"
    

    Requires allow-read permission.

  • Deno.exit

    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);
    
  • Deno.fdatasync

    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
    
  • Deno.fdatasyncSync

  • Deno.fstat

    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);
    
  • Deno.fstatSync

    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);
    
  • Deno.fsync

    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
    
  • Deno.fsyncSync

    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
    
  • Deno.ftruncate

    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
    
  • Deno.ftruncateSync

    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
    
  • Deno.inspect

    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] } }
    
  • Deno.isatty

    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);
    
  • Deno.iter deprecated

    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.

  • Deno.iterSync deprecated

    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.

  • Deno.kill

    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.

  • Deno.link

    Creates newpath as a hard link to oldpath.

    await Deno.link("old/name", "new/name");
    

    Requires allow-read and allow-write permissions.

  • Deno.linkSync

    Synchronously creates newpath as a hard link to oldpath.

    Deno.linkSync("old/name", "new/name");
    

    Requires allow-read and allow-write permissions.

  • Deno.listen

    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.

  • Deno.listenTls

    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.

  • Deno.lstat

    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.

  • Deno.lstatSync

    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.

  • Deno.makeTempDir

    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.

  • Deno.makeTempDirSync

    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.

  • Deno.makeTempFile

    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.

  • Deno.makeTempFileSync

    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.

  • Deno.memoryUsage

    Returns an object describing the memory usage of the Deno process measured in bytes.

  • Deno.metrics

    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   │
     └─────────────────────────┴────────┘
    
  • Deno.mkdir

    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.

  • Deno.mkdirSync

    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.

  • Deno.open

    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.

  • Deno.openSync

    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.

  • Deno.read

    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);
    
  • Deno.readAll deprecated

    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);
    
  • Deno.readAllSync deprecated

    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);
    
  • Deno.readDir

    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.

  • Deno.readDirSync

    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.

  • Deno.readFile

    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.

  • Deno.readFileSync

    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.

  • Deno.readLink

    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.

  • Deno.readLinkSync

    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.

  • Deno.readSync

    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);
    
  • Deno.readTextFile

    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.

  • Deno.readTextFileSync

    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.

  • Deno.realPath

    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.

  • Deno.realPathSync

    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.

  • Deno.remove

    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.

  • Deno.removeSync

    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.

  • Deno.rename

    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.

  • Deno.renameSync

    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.

  • Deno.resolveDns

  • Deno.resources

    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" }
    
  • Deno.run

    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.

  • Deno.seek

    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)
    
  • Deno.seekSync

    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)
    
  • Deno.serveHttp

    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);
    }
    
  • Deno.shutdown

    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);
    
  • Deno.startTls

    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.

  • Deno.stat

    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.

  • Deno.statSync

    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.

  • Deno.symlink

    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.

  • Deno.symlinkSync

    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.

  • Deno.test

    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");
      }
    });
    
  • Deno.truncate

    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.

  • Deno.truncateSync

    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.

  • Deno.upgradeWebSocket

    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.

  • Deno.watchFs

    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);
    }
    
  • Deno.write

    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);
    
  • Deno.writeAll deprecated

    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
    
  • Deno.writeAllSync deprecated

    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
    
  • Deno.writeFile

    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.

  • Deno.writeFileSync

    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.

  • Deno.writeSync

    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);
    
  • Deno.writeTextFile

    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.

  • Deno.writeTextFileSync

    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.

  • dispatchEvent

    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

    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();
    
  • prompt

    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.

  • queueMicrotask

    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'); });
    
  • removeEventListener

    Remove a previously registered event listener from the global scope

    const lstnr = () => { console.log('hello'); };
    addEventListener('load', lstnr);
    removeEventListener('load', lstnr);
    
  • setInterval

    Repeatedly calls a function , with a fixed time delay between each call.

    // Outputs 'hello' to the console every 500ms
    setInterval(() => { console.log('hello'); }, 500);
    
  • setTimeout

    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);
    
  • structuredClone

  • WebAssembly.compile

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

    MDN

  • WebAssembly.compileStreaming

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

    MDN

  • WebAssembly.instantiate

    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.

    MDN

  • WebAssembly.instantiateStreaming

    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.

    MDN

  • WebAssembly.validate

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

    MDN

Interfaces

Type Aliases

© 2018–2021 the Deno authors
https://doc.deno.land/deno/stable/