1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-11 16:42:21 -05:00

Fix formatting of example code in typescript declaration files (#5475)

This commit is contained in:
Siddharth Parmar 2020-05-16 21:23:48 +02:00 committed by GitHub
parent acc821c2be
commit bfd4baf2d3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 721 additions and 478 deletions

View file

@ -50,7 +50,7 @@ declare namespace Deno {
/** Register a test which will be run when `deno test` is used on the command /** 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. * line and the containing module looks like a test module.
* `fn` can be async if required. * `fn` can be async if required.
* * ```ts
* import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
* *
* Deno.test({ * Deno.test({
@ -76,6 +76,7 @@ declare namespace Deno {
* assertEquals(decoder.decode(data), "Hello world") * assertEquals(decoder.decode(data), "Hello world")
* } * }
* }); * });
* ```
*/ */
export function test(t: TestDefinition): void; export function test(t: TestDefinition): void;
@ -83,6 +84,7 @@ declare namespace Deno {
* line and the containing module looks like a test module. * line and the containing module looks like a test module.
* `fn` can be async if required. * `fn` can be async if required.
* *
* ```ts
* import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
* *
* Deno.test("My test description", ():void => { * Deno.test("My test description", ():void => {
@ -94,13 +96,16 @@ declare namespace Deno {
* const data = await Deno.readFile("hello_world.txt"); * const data = await Deno.readFile("hello_world.txt");
* assertEquals(decoder.decode(data), "Hello world") * assertEquals(decoder.decode(data), "Hello world")
* }); * });
* ```
* */ * */
export function test(name: string, fn: () => void | Promise<void>): void; export function test(name: string, fn: () => void | Promise<void>): void;
/** Exit the Deno process with optional exit code. If no exit code is supplied /** Exit the Deno process with optional exit code. If no exit code is supplied
* then Deno will exit with return code of 0. * then Deno will exit with return code of 0.
* *
* ```ts
* Deno.exit(5); * Deno.exit(5);
* ```
*/ */
export function exit(code?: number): never; export function exit(code?: number): never;
@ -108,27 +113,32 @@ declare namespace Deno {
/** Retrieve the value of an environment variable. Returns undefined if that /** Retrieve the value of an environment variable. Returns undefined if that
* key doesn't exist. * key doesn't exist.
* *
* ```ts
* console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice" * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice"
* console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined" * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined"
* * ```
* Requires `allow-env` permission. */ * Requires `allow-env` permission. */
get(key: string): string | undefined; get(key: string): string | undefined;
/** Set the value of an environment variable. /** Set the value of an environment variable.
* *
* ```ts
* Deno.env.set("SOME_VAR", "Value")); * Deno.env.set("SOME_VAR", "Value"));
* Deno.env.get("SOME_VAR"); // outputs "Value" * Deno.env.get("SOME_VAR"); // outputs "Value"
* ```
* *
* Requires `allow-env` permission. */ * Requires `allow-env` permission. */
set(key: string, value: string): void; set(key: string, value: string): void;
/** Returns a snapshot of the environment variables at invocation. /** Returns a snapshot of the environment variables at invocation.
* *
* ```ts
* Deno.env.set("TEST_VAR", "A"); * Deno.env.set("TEST_VAR", "A");
* const myEnv = Deno.env.toObject(); * const myEnv = Deno.env.toObject();
* console.log(myEnv.SHELL); * console.log(myEnv.SHELL);
* Deno.env.set("TEST_VAR", "B"); * Deno.env.set("TEST_VAR", "B");
* console.log(myEnv.TEST_VAR); // outputs "A" * console.log(myEnv.TEST_VAR); // outputs "A"
* ```
* *
* Requires `allow-env` permission. */ * Requires `allow-env` permission. */
toObject(): { [index: string]: string }; toObject(): { [index: string]: string };
@ -137,7 +147,9 @@ declare namespace Deno {
/** /**
* Returns the path to the current deno executable. * Returns the path to the current deno executable.
* *
* ```ts
* console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno" * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno"
* ```
* *
* Requires `allow-read` permission. * Requires `allow-read` permission.
*/ */
@ -146,9 +158,11 @@ declare namespace Deno {
/** /**
* Change the current working directory to the specified path. * Change the current working directory to the specified path.
* *
* ```ts
* Deno.chdir("/home/userA"); * Deno.chdir("/home/userA");
* Deno.chdir("../userB"); * Deno.chdir("../userB");
* Deno.chdir("C:\\Program Files (x86)\\Java"); * Deno.chdir("C:\\Program Files (x86)\\Java");
* ```
* *
* Throws `Deno.errors.NotFound` if directory not found. * Throws `Deno.errors.NotFound` if directory not found.
* Throws `Deno.errors.PermissionDenied` if the user does not have access * Throws `Deno.errors.PermissionDenied` if the user does not have access
@ -164,7 +178,9 @@ declare namespace Deno {
* If the current directory can be reached via multiple paths (due to symbolic * If the current directory can be reached via multiple paths (due to symbolic
* links), `cwd()` may return any one of them. * links), `cwd()` may return any one of them.
* *
* ```ts
* const currentWorkingDirectory = Deno.cwd(); * const currentWorkingDirectory = Deno.cwd();
* ```
* *
* Throws `Deno.errors.NotFound` if directory not available. * Throws `Deno.errors.NotFound` if directory not available.
* *
@ -289,10 +305,12 @@ declare namespace Deno {
* an error occurs. It resolves to the number of bytes copied or rejects with * an error occurs. It resolves to the number of bytes copied or rejects with
* the first error encountered while copying. * the first error encountered while copying.
* *
* ```ts
* const source = await Deno.open("my_file.txt"); * const source = await Deno.open("my_file.txt");
* const buffer = new Deno.Buffer() * const buffer = new Deno.Buffer()
* const bytesCopied1 = await Deno.copy(source, Deno.stdout); * const bytesCopied1 = await Deno.copy(source, Deno.stdout);
* const bytesCopied2 = await Deno.copy(source, buffer); * const bytesCopied2 = await Deno.copy(source, buffer);
* ```
* *
* @param src The source to copy from * @param src The source to copy from
* @param dst The destination to copy to * @param dst The destination to copy to
@ -308,15 +326,18 @@ declare namespace Deno {
/** Turns a Reader, `r`, into an async iterator. /** Turns a Reader, `r`, into an async iterator.
* *
* ```ts
* let f = await Deno.open("/etc/passwd"); * let f = await Deno.open("/etc/passwd");
* for await (const chunk of Deno.iter(f)) { * for await (const chunk of Deno.iter(f)) {
* console.log(chunk); * console.log(chunk);
* } * }
* f.close(); * f.close();
* ```
* *
* Second argument can be used to tune size of a buffer. * Second argument can be used to tune size of a buffer.
* Default size of the buffer is 32kB. * Default size of the buffer is 32kB.
* *
* ```ts
* let f = await Deno.open("/etc/passwd"); * let f = await Deno.open("/etc/passwd");
* const iter = Deno.iter(f, { * const iter = Deno.iter(f, {
* bufSize: 1024 * 1024 * bufSize: 1024 * 1024
@ -325,6 +346,7 @@ declare namespace Deno {
* console.log(chunk); * console.log(chunk);
* } * }
* f.close(); * f.close();
* ```
* *
* Iterator uses an internal buffer of fixed size for efficiency; it returns * 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 * a view on that buffer on each iteration. It is therefore caller's
@ -340,15 +362,18 @@ declare namespace Deno {
/** Turns a ReaderSync, `r`, into an iterator. /** Turns a ReaderSync, `r`, into an iterator.
* *
* ```ts
* let f = Deno.openSync("/etc/passwd"); * let f = Deno.openSync("/etc/passwd");
* for (const chunk of Deno.iterSync(reader)) { * for (const chunk of Deno.iterSync(reader)) {
* console.log(chunk); * console.log(chunk);
* } * }
* f.close(); * f.close();
* ```
* *
* Second argument can be used to tune size of a buffer. * Second argument can be used to tune size of a buffer.
* Default size of the buffer is 32kB. * Default size of the buffer is 32kB.
* *
* ```ts
* let f = await Deno.open("/etc/passwd"); * let f = await Deno.open("/etc/passwd");
* const iter = Deno.iterSync(f, { * const iter = Deno.iterSync(f, {
* bufSize: 1024 * 1024 * bufSize: 1024 * 1024
@ -357,6 +382,7 @@ declare namespace Deno {
* console.log(chunk); * console.log(chunk);
* } * }
* f.close(); * f.close();
* ```
* *
* Iterator uses an internal buffer of fixed size for efficiency; it returns * 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 * a view on that buffer on each iteration. It is therefore caller's
@ -375,9 +401,11 @@ declare namespace Deno {
* open options. It is the callers responsibility to close the file when finished * open options. It is the callers responsibility to close the file when finished
* with it. * with it.
* *
* ```ts
* const file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
* // Do work with file * // Do work with file
* Deno.close(file.rid); * Deno.close(file.rid);
* ```
* *
* Requires `allow-read` and/or `allow-write` permissions depending on options. * Requires `allow-read` and/or `allow-write` permissions depending on options.
*/ */
@ -388,9 +416,11 @@ declare namespace Deno {
* open options. It is the callers responsibility to close the file when finished * open options. It is the callers responsibility to close the file when finished
* with it. * with it.
* *
* ```ts
* const file = await Deno.open("/foo/bar.txt", { read: true, write: true }); * const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
* // Do work with file * // Do work with file
* Deno.close(file.rid); * Deno.close(file.rid);
* ```
* *
* Requires `allow-read` and/or `allow-write` permissions depending on options. * Requires `allow-read` and/or `allow-write` permissions depending on options.
*/ */
@ -399,7 +429,9 @@ declare namespace Deno {
/** Creates a file if none exists or truncates an existing file and returns /** Creates a file if none exists or truncates an existing file and returns
* an instance of `Deno.File`. * an instance of `Deno.File`.
* *
* ```ts
* const file = Deno.createSync("/foo/bar.txt"); * const file = Deno.createSync("/foo/bar.txt");
* ```
* *
* Requires `allow-read` and `allow-write` permissions. * Requires `allow-read` and `allow-write` permissions.
*/ */
@ -408,7 +440,9 @@ declare namespace Deno {
/** Creates a file if none exists or truncates an existing file and resolves to /** Creates a file if none exists or truncates an existing file and resolves to
* an instance of `Deno.File`. * an instance of `Deno.File`.
* *
* ```ts
* const file = await Deno.create("/foo/bar.txt"); * const file = await Deno.create("/foo/bar.txt");
* ```
* *
* Requires `allow-read` and `allow-write` permissions. * Requires `allow-read` and `allow-write` permissions.
*/ */
@ -422,12 +456,14 @@ declare namespace Deno {
* It is possible for a read to successfully return with `0` bytes. This does * It is possible for a read to successfully return with `0` bytes. This does
* not indicate EOF. * not indicate EOF.
* *
* ```ts
* // if "/foo/bar.txt" contains the text "hello world": * // if "/foo/bar.txt" contains the text "hello world":
* const file = Deno.openSync("/foo/bar.txt"); * const file = Deno.openSync("/foo/bar.txt");
* const buf = new Uint8Array(100); * const buf = new Uint8Array(100);
* const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
* const text = new TextDecoder().decode(buf); // "hello world" * const text = new TextDecoder().decode(buf); // "hello world"
* Deno.close(file.rid); * Deno.close(file.rid);
* ```
*/ */
export function readSync(rid: number, buffer: Uint8Array): number | null; export function readSync(rid: number, buffer: Uint8Array): number | null;
@ -439,12 +475,14 @@ declare namespace Deno {
* It is possible for a read to successfully return with `0` bytes. This does * It is possible for a read to successfully return with `0` bytes. This does
* not indicate EOF. * not indicate EOF.
* *
* ```ts
* // if "/foo/bar.txt" contains the text "hello world": * // if "/foo/bar.txt" contains the text "hello world":
* const file = await Deno.open("/foo/bar.txt"); * const file = await Deno.open("/foo/bar.txt");
* const buf = new Uint8Array(100); * const buf = new Uint8Array(100);
* const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
* const text = new TextDecoder().decode(buf); // "hello world" * const text = new TextDecoder().decode(buf); // "hello world"
* Deno.close(file.rid); * Deno.close(file.rid);
* ```
*/ */
export function read(rid: number, buffer: Uint8Array): Promise<number | null>; export function read(rid: number, buffer: Uint8Array): Promise<number | null>;
@ -453,11 +491,13 @@ declare namespace Deno {
* *
* Returns the number of bytes written. * Returns the number of bytes written.
* *
* ```ts
* const encoder = new TextEncoder(); * const encoder = new TextEncoder();
* const data = encoder.encode("Hello world"); * const data = encoder.encode("Hello world");
* const file = Deno.openSync("/foo/bar.txt"); * const file = Deno.openSync("/foo/bar.txt");
* const bytesWritten = Deno.writeSync(file.rid, data); // 11 * const bytesWritten = Deno.writeSync(file.rid, data); // 11
* Deno.close(file.rid); * Deno.close(file.rid);
* ```
*/ */
export function writeSync(rid: number, data: Uint8Array): number; export function writeSync(rid: number, data: Uint8Array): number;
@ -465,11 +505,13 @@ declare namespace Deno {
* *
* Resolves to the number of bytes written. * Resolves to the number of bytes written.
* *
* ```ts
* const encoder = new TextEncoder(); * const encoder = new TextEncoder();
* const data = encoder.encode("Hello world"); * const data = encoder.encode("Hello world");
* const file = await Deno.open("/foo/bar.txt"); * const file = await Deno.open("/foo/bar.txt");
* const bytesWritten = await Deno.write(file.rid, data); // 11 * const bytesWritten = await Deno.write(file.rid, data); // 11
* Deno.close(file.rid); * Deno.close(file.rid);
* ```
*/ */
export function write(rid: number, data: Uint8Array): Promise<number>; export function write(rid: number, data: Uint8Array): Promise<number>;
@ -477,6 +519,7 @@ declare namespace Deno {
* given by `whence`. The new position within the resource (bytes from the * given by `whence`. The new position within the resource (bytes from the
* start) is returned. * start) is returned.
* *
* ```ts
* const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true}); * const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
* Deno.writeSync(file.rid, new TextEncoder().encode("Hello world")); * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
* // advance cursor 6 bytes * // advance cursor 6 bytes
@ -485,9 +528,11 @@ declare namespace Deno {
* const buf = new Uint8Array(100); * const buf = new Uint8Array(100);
* file.readSync(buf); * file.readSync(buf);
* console.log(new TextDecoder().decode(buf)); // "world" * console.log(new TextDecoder().decode(buf)); // "world"
* ```
* *
* The seek modes work as follows: * The seek modes work as follows:
* *
* ```ts
* // Given file.rid pointing to file with "Hello world", which is 11 bytes long: * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
* // Seek 6 bytes from the start of the file * // Seek 6 bytes from the start of the file
* console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6" * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
@ -495,6 +540,7 @@ declare namespace Deno {
* console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8" * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
* // Seek backwards 2 bytes from the end of the file * // 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) * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
* ```
*/ */
export function seekSync( export function seekSync(
rid: number, rid: number,
@ -505,6 +551,7 @@ declare namespace Deno {
/** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`. /** 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). * The call resolves to the new position within the resource (bytes from the start).
* *
* ```ts
* const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true}); * 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")); * await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
* // advance cursor 6 bytes * // advance cursor 6 bytes
@ -513,9 +560,11 @@ declare namespace Deno {
* const buf = new Uint8Array(100); * const buf = new Uint8Array(100);
* await file.read(buf); * await file.read(buf);
* console.log(new TextDecoder().decode(buf)); // "world" * console.log(new TextDecoder().decode(buf)); // "world"
* ```
* *
* The seek modes work as follows: * The seek modes work as follows:
* *
* ```ts
* // Given file.rid pointing to file with "Hello world", which is 11 bytes long: * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
* // Seek 6 bytes from the start of the file * // Seek 6 bytes from the start of the file
* console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6" * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6"
@ -523,6 +572,7 @@ declare namespace Deno {
* console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8" * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8"
* // Seek backwards 2 bytes from the end of the file * // 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) * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
* ```
*/ */
export function seek( export function seek(
rid: number, rid: number,
@ -534,9 +584,11 @@ declare namespace Deno {
* as via opening or creating a file. Closing a file when you are finished * as via opening or creating a file. Closing a file when you are finished
* with it is important to avoid leaking resources. * with it is important to avoid leaking resources.
* *
* ```ts
* const file = await Deno.open("my_file.txt"); * const file = await Deno.open("my_file.txt");
* // do work with "file" object * // do work with "file" object
* Deno.close(file.rid); * Deno.close(file.rid);
* ````
*/ */
export function close(rid: number): void; export function close(rid: number): void;
@ -606,6 +658,7 @@ declare namespace Deno {
* *
* Check if a given resource id (`rid`) is a TTY. * Check if a given resource id (`rid`) is a TTY.
* *
* ```ts
* // This example is system and context specific * // This example is system and context specific
* const nonTTYRid = Deno.openSync("my_file.txt").rid; * const nonTTYRid = Deno.openSync("my_file.txt").rid;
* const ttyRid = Deno.openSync("/dev/tty6").rid; * const ttyRid = Deno.openSync("/dev/tty6").rid;
@ -613,6 +666,7 @@ declare namespace Deno {
* console.log(Deno.isatty(ttyRid)); // true * console.log(Deno.isatty(ttyRid)); // true
* Deno.close(nonTTYRid); * Deno.close(nonTTYRid);
* Deno.close(ttyRid); * Deno.close(ttyRid);
* ```
*/ */
export function isatty(rid: number): boolean; export function isatty(rid: number): boolean;
@ -697,6 +751,7 @@ declare namespace Deno {
/** Read Reader `r` until EOF (`null`) and resolve to the content as /** Read Reader `r` until EOF (`null`) and resolve to the content as
* Uint8Array`. * Uint8Array`.
* *
* ```ts
* // Example from stdin * // Example from stdin
* const stdinContent = await Deno.readAll(Deno.stdin); * const stdinContent = await Deno.readAll(Deno.stdin);
* *
@ -710,12 +765,14 @@ declare namespace Deno {
* // ... fill myData array with data * // ... fill myData array with data
* const reader = new Deno.Buffer(myData.buffer as ArrayBuffer); * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
* const bufferContent = await Deno.readAll(reader); * const bufferContent = await Deno.readAll(reader);
* ```
*/ */
export function readAll(r: Reader): Promise<Uint8Array>; export function readAll(r: Reader): Promise<Uint8Array>;
/** Synchronously reads Reader `r` until EOF (`null`) and returns the content /** Synchronously reads Reader `r` until EOF (`null`) and returns the content
* as `Uint8Array`. * as `Uint8Array`.
* *
* ```ts
* // Example from stdin * // Example from stdin
* const stdinContent = Deno.readAllSync(Deno.stdin); * const stdinContent = Deno.readAllSync(Deno.stdin);
* *
@ -729,11 +786,13 @@ declare namespace Deno {
* // ... fill myData array with data * // ... fill myData array with data
* const reader = new Deno.Buffer(myData.buffer as ArrayBuffer); * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
* const bufferContent = Deno.readAllSync(reader); * const bufferContent = Deno.readAllSync(reader);
* ```
*/ */
export function readAllSync(r: ReaderSync): Uint8Array; export function readAllSync(r: ReaderSync): Uint8Array;
/** Write all the content of the array buffer (`arr`) to the writer (`w`). /** Write all the content of the array buffer (`arr`) to the writer (`w`).
* *
* ```ts
* // Example writing to stdout * // Example writing to stdout
* const contentBytes = new TextEncoder().encode("Hello World"); * const contentBytes = new TextEncoder().encode("Hello World");
* await Deno.writeAll(Deno.stdout, contentBytes); * await Deno.writeAll(Deno.stdout, contentBytes);
@ -749,12 +808,14 @@ declare namespace Deno {
* const writer = new Deno.Buffer(); * const writer = new Deno.Buffer();
* await Deno.writeAll(writer, contentBytes); * await Deno.writeAll(writer, contentBytes);
* console.log(writer.bytes().length); // 11 * console.log(writer.bytes().length); // 11
* ```
*/ */
export function writeAll(w: Writer, arr: Uint8Array): Promise<void>; export function writeAll(w: Writer, arr: Uint8Array): Promise<void>;
/** Synchronously write all the content of the array buffer (`arr`) to the /** Synchronously write all the content of the array buffer (`arr`) to the
* writer (`w`). * writer (`w`).
* *
* ```ts
* // Example writing to stdout * // Example writing to stdout
* const contentBytes = new TextEncoder().encode("Hello World"); * const contentBytes = new TextEncoder().encode("Hello World");
* Deno.writeAllSync(Deno.stdout, contentBytes); * Deno.writeAllSync(Deno.stdout, contentBytes);
@ -770,6 +831,7 @@ declare namespace Deno {
* const writer = new Deno.Buffer(); * const writer = new Deno.Buffer();
* Deno.writeAllSync(writer, contentBytes); * Deno.writeAllSync(writer, contentBytes);
* console.log(writer.bytes().length); // 11 * console.log(writer.bytes().length); // 11
* ```
*/ */
export function writeAllSync(w: WriterSync, arr: Uint8Array): void; export function writeAllSync(w: WriterSync, arr: Uint8Array): void;
@ -789,9 +851,11 @@ declare namespace Deno {
/** Synchronously creates a new directory with the specified path. /** Synchronously creates a new directory with the specified path.
* *
* ```ts
* Deno.mkdirSync("new_dir"); * Deno.mkdirSync("new_dir");
* Deno.mkdirSync("nested/directories", { recursive: true }); * Deno.mkdirSync("nested/directories", { recursive: true });
* Deno.mkdirSync("restricted_access_dir", { mode: 0o700 }); * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });
* ```
* *
* Defaults to throwing error if the directory already exists. * Defaults to throwing error if the directory already exists.
* *
@ -800,9 +864,11 @@ declare namespace Deno {
/** Creates a new directory with the specified path. /** Creates a new directory with the specified path.
* *
* ```ts
* await Deno.mkdir("new_dir"); * await Deno.mkdir("new_dir");
* await Deno.mkdir("nested/directories", { recursive: true }); * await Deno.mkdir("nested/directories", { recursive: true });
* await Deno.mkdir("restricted_access_dir", { mode: 0o700 }); * await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
* ```
* *
* Defaults to throwing error if the directory already exists. * Defaults to throwing error if the directory already exists.
* *
@ -832,8 +898,10 @@ declare namespace Deno {
* directories. It is the caller's responsibility to remove the directory when * directories. It is the caller's responsibility to remove the directory when
* no longer needed. * no longer needed.
* *
* ```ts
* const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76 * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76
* const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
// TODO(ry) Doesn't check permissions. // TODO(ry) Doesn't check permissions.
@ -850,8 +918,10 @@ declare namespace Deno {
* directories. It is the caller's responsibility to remove the directory when * directories. It is the caller's responsibility to remove the directory when
* no longer needed. * no longer needed.
* *
* ```ts
* const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76 * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76
* const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
// TODO(ry) Doesn't check permissions. // TODO(ry) Doesn't check permissions.
@ -868,8 +938,10 @@ declare namespace Deno {
* files. It is the caller's responsibility to remove the file when no longer * files. It is the caller's responsibility to remove the file when no longer
* needed. * needed.
* *
* ```ts
* const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2 * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
* const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
export function makeTempFileSync(options?: MakeTempOptions): string; export function makeTempFileSync(options?: MakeTempOptions): string;
@ -885,8 +957,10 @@ declare namespace Deno {
* files. It is the caller's responsibility to remove the file when no longer * files. It is the caller's responsibility to remove the file when no longer
* needed. * needed.
* *
* ```ts
* const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2 * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2
* const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
export function makeTempFile(options?: MakeTempOptions): Promise<string>; export function makeTempFile(options?: MakeTempOptions): Promise<string>;
@ -894,7 +968,9 @@ declare namespace Deno {
/** Synchronously changes the permission of a specific file/directory of /** Synchronously changes the permission of a specific file/directory of
* specified path. Ignores the process's umask. * specified path. Ignores the process's umask.
* *
* ```ts
* Deno.chmodSync("/path/to/file", 0o666); * Deno.chmodSync("/path/to/file", 0o666);
* ```
* *
* For a full description, see [chmod](#chmod) * For a full description, see [chmod](#chmod)
* *
@ -906,7 +982,9 @@ declare namespace Deno {
/** Changes the permission of a specific file/directory of specified path. /** Changes the permission of a specific file/directory of specified path.
* Ignores the process's umask. * Ignores the process's umask.
* *
* ```ts
* await Deno.chmod("/path/to/file", 0o666); * await Deno.chmod("/path/to/file", 0o666);
* ```
* *
* The mode is a sequence of 3 octal numbers. The first/left-most number * 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 * specifies the permissions for the owner. The second number specifies the
@ -934,7 +1012,9 @@ declare namespace Deno {
/** Synchronously change owner of a regular file or directory. This functionality /** Synchronously change owner of a regular file or directory. This functionality
* is not available on Windows. * is not available on Windows.
* *
* ```ts
* Deno.chownSync("myFile.txt", 1000, 1002); * Deno.chownSync("myFile.txt", 1000, 1002);
* ```
* *
* Requires `allow-write` permission. * Requires `allow-write` permission.
* *
@ -949,7 +1029,9 @@ declare namespace Deno {
/** Change owner of a regular file or directory. This functionality /** Change owner of a regular file or directory. This functionality
* is not available on Windows. * is not available on Windows.
* *
* ```ts
* await Deno.chown("myFile.txt", 1000, 1002); * await Deno.chown("myFile.txt", 1000, 1002);
* ```
* *
* Requires `allow-write` permission. * Requires `allow-write` permission.
* *
@ -969,8 +1051,10 @@ declare namespace Deno {
/** Synchronously removes the named file or directory. /** Synchronously removes the named file or directory.
* *
* ```ts
* Deno.removeSync("/path/to/empty_dir/or/file"); * Deno.removeSync("/path/to/empty_dir/or/file");
* Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true }); * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });
* ```
* *
* Throws error if permission denied, path not found, or path is a non-empty * Throws error if permission denied, path not found, or path is a non-empty
* directory and the `recursive` option isn't set to `true`. * directory and the `recursive` option isn't set to `true`.
@ -980,8 +1064,10 @@ declare namespace Deno {
/** Removes the named file or directory. /** Removes the named file or directory.
* *
* ```ts
* await Deno.remove("/path/to/empty_dir/or/file"); * await Deno.remove("/path/to/empty_dir/or/file");
* await Deno.remove("/path/to/populated_dir/or/file", { recursive: true }); * 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 * Throws error if permission denied, path not found, or path is a non-empty
* directory and the `recursive` option isn't set to `true`. * directory and the `recursive` option isn't set to `true`.
@ -994,7 +1080,9 @@ declare namespace Deno {
* `renameSync()` replaces it. OS-specific restrictions may apply when * `renameSync()` replaces it. OS-specific restrictions may apply when
* `oldpath` and `newpath` are in different directories. * `oldpath` and `newpath` are in different directories.
* *
* ```ts
* Deno.renameSync("old/path", "new/path"); * Deno.renameSync("old/path", "new/path");
* ```
* *
* On Unix, this operation does not follow symlinks at either path. * On Unix, this operation does not follow symlinks at either path.
* *
@ -1009,7 +1097,9 @@ declare namespace Deno {
* OS-specific restrictions may apply when `oldpath` and `newpath` are in * OS-specific restrictions may apply when `oldpath` and `newpath` are in
* different directories. * different directories.
* *
* ```ts
* await Deno.rename("old/path", "new/path"); * await Deno.rename("old/path", "new/path");
* ```
* *
* On Unix, this operation does not follow symlinks at either path. * On Unix, this operation does not follow symlinks at either path.
* *
@ -1022,8 +1112,10 @@ declare namespace Deno {
/** Synchronously reads and returns the entire contents of a file as utf8 encoded string /** Synchronously reads and returns the entire contents of a file as utf8 encoded string
* encoded string. Reading a directory returns an empty string. * encoded string. Reading a directory returns an empty string.
* *
* ```ts
* const data = Deno.readTextFileSync("hello.txt"); * const data = Deno.readTextFileSync("hello.txt");
* console.log(data); * console.log(data);
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function readTextFileSync(path: string): string; export function readTextFileSync(path: string): string;
@ -1031,8 +1123,10 @@ declare namespace Deno {
/** Asynchronously reads and returns the entire contents of a file as a utf8 /** Asynchronously reads and returns the entire contents of a file as a utf8
* encoded string. Reading a directory returns an empty data array. * encoded string. Reading a directory returns an empty data array.
* *
* ```ts
* const data = await Deno.readTextFile("hello.txt"); * const data = await Deno.readTextFile("hello.txt");
* console.log(data); * console.log(data);
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function readTextFile(path: string): Promise<string>; export function readTextFile(path: string): Promise<string>;
@ -1041,9 +1135,11 @@ declare namespace Deno {
* of bytes. `TextDecoder` can be used to transform the bytes to string if * of bytes. `TextDecoder` can be used to transform the bytes to string if
* required. Reading a directory returns an empty data array. * required. Reading a directory returns an empty data array.
* *
* ```ts
* const decoder = new TextDecoder("utf-8"); * const decoder = new TextDecoder("utf-8");
* const data = Deno.readFileSync("hello.txt"); * const data = Deno.readFileSync("hello.txt");
* console.log(decoder.decode(data)); * console.log(decoder.decode(data));
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function readFileSync(path: string): Uint8Array; export function readFileSync(path: string): Uint8Array;
@ -1052,9 +1148,11 @@ declare namespace Deno {
* `TextDecoder` can be used to transform the bytes to string if required. * `TextDecoder` can be used to transform the bytes to string if required.
* Reading a directory returns an empty data array. * Reading a directory returns an empty data array.
* *
* ```ts
* const decoder = new TextDecoder("utf-8"); * const decoder = new TextDecoder("utf-8");
* const data = await Deno.readFile("hello.txt"); * const data = await Deno.readFile("hello.txt");
* console.log(decoder.decode(data)); * console.log(decoder.decode(data));
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function readFile(path: string): Promise<Uint8Array>; export function readFile(path: string): Promise<Uint8Array>;
@ -1126,24 +1224,28 @@ declare namespace Deno {
/** Returns absolute normalized path, with symbolic links resolved. /** Returns absolute normalized path, with symbolic links resolved.
* *
* ```ts
* // e.g. given /home/alice/file.txt and current directory /home/alice * // e.g. given /home/alice/file.txt and current directory /home/alice
* Deno.symlinkSync("file.txt", "symlink_file.txt"); * Deno.symlinkSync("file.txt", "symlink_file.txt");
* const realPath = Deno.realPathSync("./file.txt"); * const realPath = Deno.realPathSync("./file.txt");
* const realSymLinkPath = Deno.realPathSync("./symlink_file.txt"); * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
* console.log(realPath); // outputs "/home/alice/file.txt" * console.log(realPath); // outputs "/home/alice/file.txt"
* console.log(realSymLinkPath); // outputs "/home/alice/file.txt" * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function realPathSync(path: string): string; export function realPathSync(path: string): string;
/** Resolves to the absolute normalized path, with symbolic links resolved. /** Resolves to the absolute normalized path, with symbolic links resolved.
* *
* ```ts
* // e.g. given /home/alice/file.txt and current directory /home/alice * // e.g. given /home/alice/file.txt and current directory /home/alice
* await Deno.symlink("file.txt", "symlink_file.txt"); * await Deno.symlink("file.txt", "symlink_file.txt");
* const realPath = await Deno.realPath("./file.txt"); * const realPath = await Deno.realPath("./file.txt");
* const realSymLinkPath = await Deno.realPath("./symlink_file.txt"); * const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
* console.log(realPath); // outputs "/home/alice/file.txt" * console.log(realPath); // outputs "/home/alice/file.txt"
* console.log(realSymLinkPath); // outputs "/home/alice/file.txt" * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function realPath(path: string): Promise<string>; export function realPath(path: string): Promise<string>;
@ -1158,9 +1260,11 @@ declare namespace Deno {
/** Synchronously reads the directory given by `path` and returns an iterable /** Synchronously reads the directory given by `path` and returns an iterable
* of `Deno.DirEntry`. * of `Deno.DirEntry`.
* *
* ```ts
* for (const dirEntry of Deno.readDirSync("/")) { * for (const dirEntry of Deno.readDirSync("/")) {
* console.log(dirEntry.name); * console.log(dirEntry.name);
* } * }
* ```
* *
* Throws error if `path` is not a directory. * Throws error if `path` is not a directory.
* *
@ -1170,9 +1274,11 @@ declare namespace Deno {
/** Reads the directory given by `path` and returns an async iterable of /** Reads the directory given by `path` and returns an async iterable of
* `Deno.DirEntry`. * `Deno.DirEntry`.
* *
* ```ts
* for await (const dirEntry of Deno.readDir("/")) { * for await (const dirEntry of Deno.readDir("/")) {
* console.log(dirEntry.name); * console.log(dirEntry.name);
* } * }
* ```
* *
* Throws error if `path` is not a directory. * Throws error if `path` is not a directory.
* *
@ -1183,7 +1289,9 @@ declare namespace Deno {
* specified path, by default creating a new file if needed, else overwriting. * specified path, by default creating a new file if needed, else overwriting.
* Fails if target path is a directory or is unwritable. * Fails if target path is a directory or is unwritable.
* *
* ```ts
* Deno.copyFileSync("from.txt", "to.txt"); * Deno.copyFileSync("from.txt", "to.txt");
* ```
* *
* Requires `allow-read` permission on fromPath. * Requires `allow-read` permission on fromPath.
* Requires `allow-write` permission on toPath. */ * Requires `allow-write` permission on toPath. */
@ -1193,7 +1301,9 @@ declare namespace Deno {
* by default creating a new file if needed, else overwriting. Fails if target * by default creating a new file if needed, else overwriting. Fails if target
* path is a directory or is unwritable. * path is a directory or is unwritable.
* *
* ```ts
* await Deno.copyFile("from.txt", "to.txt"); * await Deno.copyFile("from.txt", "to.txt");
* ```
* *
* Requires `allow-read` permission on fromPath. * Requires `allow-read` permission on fromPath.
* Requires `allow-write` permission on toPath. */ * Requires `allow-write` permission on toPath. */
@ -1201,8 +1311,10 @@ declare namespace Deno {
/** Returns the full path destination of the named symbolic link. /** Returns the full path destination of the named symbolic link.
* *
* ```ts
* Deno.symlinkSync("./test.txt", "./test_link.txt"); * Deno.symlinkSync("./test.txt", "./test_link.txt");
* const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt
* ```
* *
* Throws TypeError if called with a hard link * Throws TypeError if called with a hard link
* *
@ -1211,8 +1323,10 @@ declare namespace Deno {
/** Resolves to the full path destination of the named symbolic link. /** Resolves to the full path destination of the named symbolic link.
* *
* ```ts
* await Deno.symlink("./test.txt", "./test_link.txt"); * await Deno.symlink("./test.txt", "./test_link.txt");
* const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt
* ```
* *
* Throws TypeError if called with a hard link * Throws TypeError if called with a hard link
* *
@ -1223,8 +1337,10 @@ declare namespace Deno {
* symlink, information for the symlink will be returned instead of what it * symlink, information for the symlink will be returned instead of what it
* points to. * points to.
* *
* ```ts
* const fileInfo = await Deno.lstat("hello.txt"); * const fileInfo = await Deno.lstat("hello.txt");
* assert(fileInfo.isFile); * assert(fileInfo.isFile);
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function lstat(path: string): Promise<FileInfo>; export function lstat(path: string): Promise<FileInfo>;
@ -1233,8 +1349,10 @@ declare namespace Deno {
* `path` is a symlink, information for the symlink will be returned instead of * `path` is a symlink, information for the symlink will be returned instead of
* what it points to.. * what it points to..
* *
* ```ts
* const fileInfo = Deno.lstatSync("hello.txt"); * const fileInfo = Deno.lstatSync("hello.txt");
* assert(fileInfo.isFile); * assert(fileInfo.isFile);
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function lstatSync(path: string): FileInfo; export function lstatSync(path: string): FileInfo;
@ -1242,8 +1360,10 @@ declare namespace Deno {
/** Resolves to a `Deno.FileInfo` for the specified `path`. Will always /** Resolves to a `Deno.FileInfo` for the specified `path`. Will always
* follow symlinks. * follow symlinks.
* *
* ```ts
* const fileInfo = await Deno.stat("hello.txt"); * const fileInfo = await Deno.stat("hello.txt");
* assert(fileInfo.isFile); * assert(fileInfo.isFile);
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function stat(path: string): Promise<FileInfo>; export function stat(path: string): Promise<FileInfo>;
@ -1251,8 +1371,10 @@ declare namespace Deno {
/** Synchronously returns a `Deno.FileInfo` for the specified `path`. Will /** Synchronously returns a `Deno.FileInfo` for the specified `path`. Will
* always follow symlinks. * always follow symlinks.
* *
* ```ts
* const fileInfo = Deno.statSync("hello.txt"); * const fileInfo = Deno.statSync("hello.txt");
* assert(fileInfo.isFile); * assert(fileInfo.isFile);
* ```
* *
* Requires `allow-read` permission. */ * Requires `allow-read` permission. */
export function statSync(path: string): FileInfo; export function statSync(path: string): FileInfo;
@ -1272,12 +1394,14 @@ declare namespace Deno {
/** Synchronously write `data` to the given `path`, by default creating a new /** Synchronously write `data` to the given `path`, by default creating a new
* file if needed, else overwriting. * file if needed, else overwriting.
* *
* ```ts
* const encoder = new TextEncoder(); * const encoder = new TextEncoder();
* const data = encoder.encode("Hello world\n"); * const data = encoder.encode("Hello world\n");
* Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it * 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("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("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 * 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 * Requires `allow-write` permission, and `allow-read` if `options.create` is
* `false`. * `false`.
@ -1291,12 +1415,14 @@ declare namespace Deno {
/** Write `data` to the given `path`, by default creating a new file if needed, /** Write `data` to the given `path`, by default creating a new file if needed,
* else overwriting. * else overwriting.
* *
* ```ts
* const encoder = new TextEncoder(); * const encoder = new TextEncoder();
* const data = encoder.encode("Hello world\n"); * const data = encoder.encode("Hello world\n");
* await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it * 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("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("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 * 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`. * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
*/ */
@ -1309,7 +1435,9 @@ declare namespace Deno {
/** Synchronously write string `data` to the given `path`, by default creating a new file if needed, /** Synchronously write string `data` to the given `path`, by default creating a new file if needed,
* else overwriting. * else overwriting.
* *
* ```ts
* await Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it * await 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`. * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
*/ */
@ -1318,7 +1446,9 @@ declare namespace Deno {
/** Asynchronously write string `data` to the given `path`, by default creating a new file if needed, /** Asynchronously write string `data` to the given `path`, by default creating a new file if needed,
* else overwriting. * else overwriting.
* *
* ```ts
* await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it * 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`. * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
*/ */
@ -1328,6 +1458,7 @@ declare namespace Deno {
* specified `len`. If `len` is not specified then the entire file contents * specified `len`. If `len` is not specified then the entire file contents
* are truncated. * are truncated.
* *
* ```ts
* // truncate the entire file * // truncate the entire file
* Deno.truncateSync("my_file.txt"); * Deno.truncateSync("my_file.txt");
* *
@ -1337,6 +1468,7 @@ declare namespace Deno {
* Deno.truncateSync(file, 7); * Deno.truncateSync(file, 7);
* const data = Deno.readFileSync(file); * const data = Deno.readFileSync(file);
* console.log(new TextDecoder().decode(data)); * console.log(new TextDecoder().decode(data));
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
export function truncateSync(name: string, len?: number): void; export function truncateSync(name: string, len?: number): void;
@ -1344,6 +1476,7 @@ declare namespace Deno {
/** Truncates or extends the specified file, to reach the specified `len`. If /** Truncates or extends the specified file, to reach the specified `len`. If
* `len` is not specified then the entire file contents are truncated. * `len` is not specified then the entire file contents are truncated.
* *
* ```ts
* // truncate the entire file * // truncate the entire file
* await Deno.truncate("my_file.txt"); * await Deno.truncate("my_file.txt");
* *
@ -1353,6 +1486,7 @@ declare namespace Deno {
* await Deno.truncate(file, 7); * await Deno.truncate(file, 7);
* const data = await Deno.readFile(file); * const data = await Deno.readFile(file);
* console.log(new TextDecoder().decode(data)); // "Hello W" * console.log(new TextDecoder().decode(data)); // "Hello W"
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
export function truncate(name: string, len?: number): Promise<void>; export function truncate(name: string, len?: number): Promise<void>;
@ -1409,10 +1543,12 @@ declare namespace Deno {
/** Listen announces on the local transport address. /** Listen announces on the local transport address.
* *
* ```ts
* const listener1 = Deno.listen({ port: 80 }) * const listener1 = Deno.listen({ port: 80 })
* const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 }) * const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
* const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 }); * const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
* const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" }); * const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });
* ```
* *
* Requires `allow-net` permission. */ * Requires `allow-net` permission. */
export function listen( export function listen(
@ -1431,7 +1567,9 @@ declare namespace Deno {
/** Listen announces on the local transport address over TLS (transport layer /** Listen announces on the local transport address over TLS (transport layer
* security). * security).
* *
* ```ts
* const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" }); * const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" });
* ```
* *
* Requires `allow-net` permission. */ * Requires `allow-net` permission. */
export function listenTls(options: ListenTlsOptions): Listener; export function listenTls(options: ListenTlsOptions): Listener;
@ -1449,11 +1587,13 @@ declare namespace Deno {
* Connects to the hostname (default is "127.0.0.1") and port on the named * 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`). * transport (default is "tcp"), and resolves to the connection (`Conn`).
* *
* ```ts
* const conn1 = await Deno.connect({ port: 80 }); * const conn1 = await Deno.connect({ port: 80 });
* const conn2 = await Deno.connect({ hostname: "192.0.2.1", 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 conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
* const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" }); * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
* const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" }); * const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
* ```
* *
* Requires `allow-net` permission for "tcp" and `allow-read` for unix. */ * Requires `allow-net` permission for "tcp" and `allow-read` for unix. */
export function connect(options: ConnectOptions): Promise<Conn>; export function connect(options: ConnectOptions): Promise<Conn>;
@ -1473,10 +1613,12 @@ declare namespace Deno {
* cert file is optional and if not included Mozilla's root certificates will * 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) * be used (see also https://github.com/ctz/webpki-roots for specifics)
* *
* ```ts
* const conn1 = await Deno.connectTls({ port: 80 }); * const conn1 = await Deno.connectTls({ port: 80 });
* const conn2 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 }); * const conn2 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 });
* const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 }); * const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 });
* const conn4 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80}); * const conn4 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80});
* ```
* *
* Requires `allow-net` permission. * Requires `allow-net` permission.
*/ */
@ -1528,11 +1670,13 @@ declare namespace Deno {
* representations. This is an internal API and as such resource * representations. This is an internal API and as such resource
* representation has `any` type; that means it can change any time. * representation has `any` type; that means it can change any time.
* *
* ```ts
* console.log(Deno.resources()); * console.log(Deno.resources());
* // { 0: "stdin", 1: "stdout", 2: "stderr" } * // { 0: "stdin", 1: "stdout", 2: "stderr" }
* Deno.openSync('../test.file'); * Deno.openSync('../test.file');
* console.log(Deno.resources()); * console.log(Deno.resources());
* // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" } * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }
* ```
*/ */
export function resources(): ResourceMap; export function resources(): ResourceMap;
@ -1549,11 +1693,13 @@ declare namespace Deno {
* for directories, will watch the specified directory and all sub directories. * for directories, will watch the specified directory and all sub directories.
* Note that the exact ordering of the events can vary between operating systems. * Note that the exact ordering of the events can vary between operating systems.
* *
* ```ts
* const watcher = Deno.watchFs("/"); * const watcher = Deno.watchFs("/");
* for await (const event of watcher) { * for await (const event of watcher) {
* console.log(">>>> event", event); * console.log(">>>> event", event);
* // { kind: "create", paths: [ "/foo.txt" ] } * // { kind: "create", paths: [ "/foo.txt" ] }
* } * }
*```
* *
* Requires `allow-read` permission. * Requires `allow-read` permission.
*/ */
@ -1621,9 +1767,11 @@ declare namespace Deno {
/** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`, /** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`,
* an array of program arguments, the first of which is the binary. * an array of program arguments, the first of which is the binary.
* *
* ```ts
* const p = Deno.run({ * const p = Deno.run({
* cmd: ["echo", "hello"], * cmd: ["echo", "hello"],
* }); * });
* ```
* *
* Subprocess uses same working directory as parent process unless `opt.cwd` * Subprocess uses same working directory as parent process unless `opt.cwd`
* is specified. * is specified.
@ -1657,15 +1805,18 @@ declare namespace Deno {
/** Converts the input into a string that has the same format as printed by /** Converts the input into a string that has the same format as printed by
* `console.log()`. * `console.log()`.
* *
* ```ts
* const obj = {}; * const obj = {};
* obj.propA = 10; * obj.propA = 10;
* obj.propB = "hello" * obj.propB = "hello"
* const objAsString = Deno.inspect(obj); // { propA: 10, propB: "hello" } * const objAsString = Deno.inspect(obj); // { propA: 10, propB: "hello" }
* console.log(obj); // prints same value as objAsString, e.g. { propA: 10, propB: "hello" } * console.log(obj); // prints same value as objAsString, e.g. { propA: 10, propB: "hello" }
* ```
* *
* You can also register custom inspect functions, via the `customInspect` Deno * You can also register custom inspect functions, via the `customInspect` Deno
* symbol on objects, to control and customize the output. * symbol on objects, to control and customize the output.
* *
* ```ts
* class A { * class A {
* x = 10; * x = 10;
* y = "hello"; * y = "hello";
@ -1673,6 +1824,7 @@ declare namespace Deno {
* return "x=" + this.x + ", y=" + this.y; * return "x=" + this.x + ", y=" + this.y;
* } * }
* } * }
* ```
* *
* const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello" * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello"
* console.log(inStringFormat); // prints "x=10, y=hello" * console.log(inStringFormat); // prints "x=10, y=hello"

View file

@ -1005,37 +1005,47 @@ declare class TextEncoder {
interface URLSearchParams { interface URLSearchParams {
/** Appends a specified key/value pair as a new search parameter. /** Appends a specified key/value pair as a new search parameter.
* *
* ```ts
* let searchParams = new URLSearchParams(); * let searchParams = new URLSearchParams();
* searchParams.append('name', 'first'); * searchParams.append('name', 'first');
* searchParams.append('name', 'second'); * searchParams.append('name', 'second');
* ```
*/ */
append(name: string, value: string): void; append(name: string, value: string): void;
/** Deletes the given search parameter and its associated value, /** Deletes the given search parameter and its associated value,
* from the list of all search parameters. * from the list of all search parameters.
* *
* ```ts
* let searchParams = new URLSearchParams([['name', 'value']]); * let searchParams = new URLSearchParams([['name', 'value']]);
* searchParams.delete('name'); * searchParams.delete('name');
* ```
*/ */
delete(name: string): void; delete(name: string): void;
/** Returns all the values associated with a given search parameter /** Returns all the values associated with a given search parameter
* as an array. * as an array.
* *
* ```ts
* searchParams.getAll('name'); * searchParams.getAll('name');
* ```
*/ */
getAll(name: string): string[]; getAll(name: string): string[];
/** Returns the first value associated to the given search parameter. /** Returns the first value associated to the given search parameter.
* *
* ```ts
* searchParams.get('name'); * searchParams.get('name');
* ```
*/ */
get(name: string): string | null; get(name: string): string | null;
/** Returns a Boolean that indicates whether a parameter with the /** Returns a Boolean that indicates whether a parameter with the
* specified name exists. * specified name exists.
* *
* ```ts
* searchParams.has('name'); * searchParams.has('name');
* ```
*/ */
has(name: string): boolean; has(name: string): boolean;
@ -1044,7 +1054,9 @@ interface URLSearchParams {
* deletes the others. If the search parameter doesn't exist, this * deletes the others. If the search parameter doesn't exist, this
* method creates it. * method creates it.
* *
* ```ts
* searchParams.set('name', 'value'); * searchParams.set('name', 'value');
* ```
*/ */
set(name: string, value: string): void; set(name: string, value: string): void;
@ -1052,7 +1064,9 @@ interface URLSearchParams {
* return undefined. The sort order is according to Unicode code * return undefined. The sort order is according to Unicode code
* points of the keys. * points of the keys.
* *
* ```ts
* searchParams.sort(); * searchParams.sort();
* ```
*/ */
sort(): void; sort(): void;
@ -1060,10 +1074,12 @@ interface URLSearchParams {
* place and return undefined. Optionally accepts an object to use * place and return undefined. Optionally accepts an object to use
* as this when executing callback as second argument. * as this when executing callback as second argument.
* *
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]); * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* params.forEach((value, key, parent) => { * params.forEach((value, key, parent) => {
* console.log(value, key, parent); * console.log(value, key, parent);
* }); * });
* ```
* *
*/ */
forEach( forEach(
@ -1074,46 +1090,56 @@ interface URLSearchParams {
/** Returns an iterator allowing to go through all keys contained /** Returns an iterator allowing to go through all keys contained
* in this object. * in this object.
* *
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]); * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const key of params.keys()) { * for (const key of params.keys()) {
* console.log(key); * console.log(key);
* } * }
* ```
*/ */
keys(): IterableIterator<string>; keys(): IterableIterator<string>;
/** Returns an iterator allowing to go through all values contained /** Returns an iterator allowing to go through all values contained
* in this object. * in this object.
* *
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]); * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const value of params.values()) { * for (const value of params.values()) {
* console.log(value); * console.log(value);
* } * }
* ```
*/ */
values(): IterableIterator<string>; values(): IterableIterator<string>;
/** Returns an iterator allowing to go through all key/value /** Returns an iterator allowing to go through all key/value
* pairs contained in this object. * pairs contained in this object.
* *
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]); * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const [key, value] of params.entries()) { * for (const [key, value] of params.entries()) {
* console.log(key, value); * console.log(key, value);
* } * }
* ```
*/ */
entries(): IterableIterator<[string, string]>; entries(): IterableIterator<[string, string]>;
/** Returns an iterator allowing to go through all key/value /** Returns an iterator allowing to go through all key/value
* pairs contained in this object. * pairs contained in this object.
* *
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]); * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const [key, value] of params) { * for (const [key, value] of params) {
* console.log(key, value); * console.log(key, value);
* } * }
* ```
*/ */
[Symbol.iterator](): IterableIterator<[string, string]>; [Symbol.iterator](): IterableIterator<[string, string]>;
/** Returns a query string suitable for use in a URL. /** Returns a query string suitable for use in a URL.
* *
* ```ts
* searchParams.toString(); * searchParams.toString();
* ```
*/ */
toString(): string; toString(): string;
} }
@ -1206,6 +1232,8 @@ declare class Worker extends EventTarget {
* Configurable permissions are on the roadmap to be implemented. * Configurable permissions are on the roadmap to be implemented.
* *
* Example: * Example:
*
* ```ts
* // mod.ts * // mod.ts
* const worker = new Worker("./deno_worker.ts", { type: "module", deno: true }); * const worker = new Worker("./deno_worker.ts", { type: "module", deno: true });
* worker.postMessage({ cmd: "readFile", fileName: "./log.txt" }); * worker.postMessage({ cmd: "readFile", fileName: "./log.txt" });
@ -1222,6 +1250,7 @@ declare class Worker extends EventTarget {
* const fileContents = new TextDecoder().decode(buf); * const fileContents = new TextDecoder().decode(buf);
* console.log(fileContents); * console.log(fileContents);
* } * }
* ```
* *
* // log.txt * // log.txt
* hello world * hello world
@ -1246,8 +1275,10 @@ declare namespace performance {
* *
* Use the flag --allow-hrtime return a precise value. * Use the flag --allow-hrtime return a precise value.
* *
* ```ts
* const t = performance.now(); * const t = performance.now();
* console.log(`${t} ms since start!`); * console.log(`${t} ms since start!`);
* ```
*/ */
export function now(): number; export function now(): number;
} }

View file

@ -11,9 +11,11 @@ declare namespace Deno {
* Retrieve the process umask. If `mask` is provided, sets the process umask. * Retrieve the process umask. If `mask` is provided, sets the process umask.
* This call always returns what the umask was before the call. * This call always returns what the umask was before the call.
* *
* ```ts
* console.log(Deno.umask()); // e.g. 18 (0o022) * console.log(Deno.umask()); // e.g. 18 (0o022)
* const prevUmaskValue = Deno.umask(0o077); // e.g. 18 (0o022) * const prevUmaskValue = Deno.umask(0o077); // e.g. 18 (0o022)
* console.log(Deno.umask()); // e.g. 63 (0o077) * console.log(Deno.umask()); // e.g. 63 (0o077)
* ```
* *
* NOTE: This API is not implemented on Windows * NOTE: This API is not implemented on Windows
*/ */
@ -21,7 +23,9 @@ declare namespace Deno {
/** Synchronously creates `newpath` as a hard link to `oldpath`. /** Synchronously creates `newpath` as a hard link to `oldpath`.
* *
* ```ts
* Deno.linkSync("old/name", "new/name"); * Deno.linkSync("old/name", "new/name");
* ```
* *
* Requires `allow-read` and `allow-write` permissions. */ * Requires `allow-read` and `allow-write` permissions. */
export function linkSync(oldpath: string, newpath: string): void; export function linkSync(oldpath: string, newpath: string): void;
@ -30,7 +34,9 @@ declare namespace Deno {
* *
* **UNSTABLE**: needs security review. * **UNSTABLE**: needs security review.
* *
* ```ts
* await Deno.link("old/name", "new/name"); * await Deno.link("old/name", "new/name");
* ```
* *
* Requires `allow-read` and `allow-write` permissions. */ * Requires `allow-read` and `allow-write` permissions. */
export function link(oldpath: string, newpath: string): Promise<void>; export function link(oldpath: string, newpath: string): Promise<void>;
@ -46,7 +52,9 @@ declare namespace Deno {
* *
* NOTE: This function is not yet implemented on Windows. * NOTE: This function is not yet implemented on Windows.
* *
* ```ts
* Deno.symlinkSync("old/name", "new/name"); * Deno.symlinkSync("old/name", "new/name");
* ```
* *
* Requires `allow-read` and `allow-write` permissions. */ * Requires `allow-read` and `allow-write` permissions. */
export function symlinkSync( export function symlinkSync(
@ -66,7 +74,9 @@ declare namespace Deno {
* *
* NOTE: This function is not yet implemented on Windows. * NOTE: This function is not yet implemented on Windows.
* *
* ```ts
* await Deno.symlink("old/name", "new/name"); * await Deno.symlink("old/name", "new/name");
* ```
* *
* Requires `allow-read` and `allow-write` permissions. */ * Requires `allow-read` and `allow-write` permissions. */
export function symlink( export function symlink(
@ -100,7 +110,9 @@ declare namespace Deno {
* *
* Returns the user and platform specific directories. * Returns the user and platform specific directories.
* *
* ```ts
* const homeDirectory = Deno.dir("home"); * const homeDirectory = Deno.dir("home");
* ```
* *
* Requires `allow-env` permission. * Requires `allow-env` permission.
* *
@ -248,7 +260,9 @@ declare namespace Deno {
* is no load. On Windows, the three values are always the same and represent * is no load. On Windows, the three values are always the same and represent
* the current load, not the 1, 5 and 15 minute load averages. * the current load, not the 1, 5 and 15 minute load averages.
* *
* ```ts
* console.log(Deno.loadavg()); // e.g. [ 0.71, 0.44, 0.44 ] * console.log(Deno.loadavg()); // e.g. [ 0.71, 0.44, 0.44 ]
* ```
* *
* Requires `allow-env` permission. * Requires `allow-env` permission.
* *
@ -259,7 +273,9 @@ declare namespace Deno {
/** Returns the release version of the Operating System. /** Returns the release version of the Operating System.
* *
* ```ts
* console.log(Deno.osRelease()); * console.log(Deno.osRelease());
* ```
* *
* Requires `allow-env` permission. * Requires `allow-env` permission.
* *
@ -272,10 +288,12 @@ declare namespace Deno {
* *
* Open and initialize a plugin. * Open and initialize a plugin.
* *
* ```ts
* const rid = Deno.openPlugin("./path/to/some/plugin.so"); * const rid = Deno.openPlugin("./path/to/some/plugin.so");
* const opId = Deno.core.ops()["some_op"]; * const opId = Deno.core.ops()["some_op"];
* const response = Deno.core.dispatch(opId, new Uint8Array([1,2,3,4])); * const response = Deno.core.dispatch(opId, new Uint8Array([1,2,3,4]));
* console.log(`Response from plugin ${response}`); * console.log(`Response from plugin ${response}`);
* ```
* *
* Requires `allow-plugin` permission. * Requires `allow-plugin` permission.
* *
@ -340,9 +358,11 @@ declare namespace Deno {
* Format an array of diagnostic items and return them as a single string in a * Format an array of diagnostic items and return them as a single string in a
* user friendly format. * user friendly format.
* *
* ```ts
* const [diagnostics, result] = Deno.compile("file_with_compile_issues.ts"); * const [diagnostics, result] = Deno.compile("file_with_compile_issues.ts");
* console.table(diagnostics); // Prints raw diagnostic data * console.table(diagnostics); // Prints raw diagnostic data
* console.log(Deno.formatDiagnostics(diagnostics)); // User friendly output of diagnostics * console.log(Deno.formatDiagnostics(diagnostics)); // User friendly output of diagnostics
* ```
* *
* @param items An array of diagnostic items to format * @param items An array of diagnostic items to format
*/ */
@ -541,6 +561,7 @@ declare namespace Deno {
* irrespective of if sources are provided on the call. Like other Deno * irrespective of if sources are provided on the call. Like other Deno
* modules, there is no "magical" resolution. For example: * modules, there is no "magical" resolution. For example:
* *
* ```ts
* Deno.compile( * Deno.compile(
* "./foo.js", * "./foo.js",
* undefined, * undefined,
@ -548,6 +569,7 @@ declare namespace Deno {
* types: [ "./foo.d.ts", "https://deno.land/x/example/types.d.ts" ] * types: [ "./foo.d.ts", "https://deno.land/x/example/types.d.ts" ]
* } * }
* ); * );
* ```
*/ */
types?: string[]; types?: string[];
} }
@ -569,9 +591,11 @@ declare namespace Deno {
* type checking and validation, it effectively "strips" the types from the * type checking and validation, it effectively "strips" the types from the
* file. * file.
* *
* ```ts
* const results = await Deno.transpileOnly({ * const results = await Deno.transpileOnly({
* "foo.ts": `const foo: string = "foo";` * "foo.ts": `const foo: string = "foo";`
* }); * });
* ```
* *
* @param sources A map where the key is the filename and the value is the text * @param sources A map where the key is the filename and the value is the text
* to transpile. The filename is only used in the transpile and * to transpile. The filename is only used in the transpile and
@ -598,12 +622,14 @@ declare namespace Deno {
* the key is the module name and the value is the content. The extension of * the key is the module name and the value is the content. The extension of
* the module name will be used to determine the media type of the module. * the module name will be used to determine the media type of the module.
* *
* ```ts
* const [ maybeDiagnostics1, output1 ] = await Deno.compile("foo.ts"); * const [ maybeDiagnostics1, output1 ] = await Deno.compile("foo.ts");
* *
* const [ maybeDiagnostics2, output2 ] = await Deno.compile("/foo.ts", { * const [ maybeDiagnostics2, output2 ] = await Deno.compile("/foo.ts", {
* "/foo.ts": `export * from "./bar.ts";`, * "/foo.ts": `export * from "./bar.ts";`,
* "/bar.ts": `export const bar = "bar";` * "/bar.ts": `export const bar = "bar";`
* }); * });
* ```
* *
* @param rootName The root name of the module which will be used as the * @param rootName The root name of the module which will be used as the
* "starting point". If no `sources` is specified, Deno will * "starting point". If no `sources` is specified, Deno will
@ -638,6 +664,7 @@ declare namespace Deno {
* the key is the module name and the value is the content. The extension of the * the key is the module name and the value is the content. The extension of the
* module name will be used to determine the media type of the module. * module name will be used to determine the media type of the module.
* *
* ```ts
* // equivalent to "deno bundle foo.ts" from the command line * // equivalent to "deno bundle foo.ts" from the command line
* const [ maybeDiagnostics1, output1 ] = await Deno.bundle("foo.ts"); * const [ maybeDiagnostics1, output1 ] = await Deno.bundle("foo.ts");
* *
@ -645,6 +672,7 @@ declare namespace Deno {
* "/foo.ts": `export * from "./bar.ts";`, * "/foo.ts": `export * from "./bar.ts";`,
* "/bar.ts": `export const bar = "bar";` * "/bar.ts": `export const bar = "bar";`
* }); * });
* ```
* *
* @param rootName The root name of the module which will be used as the * @param rootName The root name of the module which will be used as the
* "starting point". If no `sources` is specified, Deno will * "starting point". If no `sources` is specified, Deno will
@ -691,12 +719,14 @@ declare namespace Deno {
* *
* An example: * An example:
* *
* ```ts
* const orig = Deno.applySourceMap({ * const orig = Deno.applySourceMap({
* fileName: "file://my/module.ts", * fileName: "file://my/module.ts",
* lineNumber: 5, * lineNumber: 5,
* columnNumber: 15 * columnNumber: 15
* }); * });
* console.log(`${orig.filename}:${orig.line}:${orig.column}`); * console.log(`${orig.filename}:${orig.line}:${orig.column}`);
* ```
*/ */
export function applySourceMap(location: Location): Location; export function applySourceMap(location: Location): Location;
@ -793,24 +823,30 @@ declare namespace Deno {
* Returns the stream of the given signal number. You can use it as an async * Returns the stream of the given signal number. You can use it as an async
* iterator. * iterator.
* *
* ```ts
* for await (const _ of Deno.signal(Deno.Signal.SIGTERM)) { * for await (const _ of Deno.signal(Deno.Signal.SIGTERM)) {
* console.log("got SIGTERM!"); * console.log("got SIGTERM!");
* } * }
* ```
* *
* You can also use it as a promise. In this case you can only receive the * You can also use it as a promise. In this case you can only receive the
* first one. * first one.
* *
* ```ts
* await Deno.signal(Deno.Signal.SIGTERM); * await Deno.signal(Deno.Signal.SIGTERM);
* console.log("SIGTERM received!") * console.log("SIGTERM received!")
* ```
* *
* If you want to stop receiving the signals, you can use `.dispose()` method * If you want to stop receiving the signals, you can use `.dispose()` method
* of the signal stream object. * of the signal stream object.
* *
* ```ts
* const sig = Deno.signal(Deno.Signal.SIGTERM); * const sig = Deno.signal(Deno.Signal.SIGTERM);
* setTimeout(() => { sig.dispose(); }, 5000); * setTimeout(() => { sig.dispose(); }, 5000);
* for await (const _ of sig) { * for await (const _ of sig) {
* console.log("SIGTERM!") * console.log("SIGTERM!")
* } * }
* ```
* *
* The above for-await loop exits after 5 seconds when `sig.dispose()` is * The above for-await loop exits after 5 seconds when `sig.dispose()` is
* called. * called.
@ -875,7 +911,9 @@ declare namespace Deno {
* Reading from a TTY device in raw mode is faster than reading from a TTY * Reading from a TTY device in raw mode is faster than reading from a TTY
* device in canonical mode. * device in canonical mode.
* *
* ```ts
* Deno.setRaw(myTTY.rid, true); * Deno.setRaw(myTTY.rid, true);
* ```
*/ */
export function setRaw(rid: number, mode: boolean): void; export function setRaw(rid: number, mode: boolean): void;
@ -885,7 +923,9 @@ declare namespace Deno {
* of a file system object referenced by `path`. Given times are either in * of a file system object referenced by `path`. Given times are either in
* seconds (UNIX epoch time) or as `Date` objects. * seconds (UNIX epoch time) or as `Date` objects.
* *
* ```ts
* Deno.utimeSync("myfile.txt", 1556495550, new Date()); * Deno.utimeSync("myfile.txt", 1556495550, new Date());
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
export function utimeSync( export function utimeSync(
@ -900,7 +940,9 @@ declare namespace Deno {
* system object referenced by `path`. Given times are either in seconds * system object referenced by `path`. Given times are either in seconds
* (UNIX epoch time) or as `Date` objects. * (UNIX epoch time) or as `Date` objects.
* *
* ```ts
* await Deno.utime("myfile.txt", 1556495550, new Date()); * await Deno.utime("myfile.txt", 1556495550, new Date());
* ```
* *
* Requires `allow-write` permission. */ * Requires `allow-write` permission. */
export function utime( export function utime(
@ -927,9 +969,11 @@ declare namespace Deno {
* *
* Matches behavior of POSIX shutdown(3). * Matches behavior of POSIX shutdown(3).
* *
* ```ts
* const listener = Deno.listen({ port: 80 }); * const listener = Deno.listen({ port: 80 });
* const conn = await listener.accept(); * const conn = await listener.accept();
* Deno.shutdown(conn.rid, Deno.ShutdownMode.Write); * Deno.shutdown(conn.rid, Deno.ShutdownMode.Write);
* ```
*/ */
export function shutdown(rid: number, how: ShutdownMode): Promise<void>; export function shutdown(rid: number, how: ShutdownMode): Promise<void>;
@ -964,7 +1008,9 @@ declare namespace Deno {
* *
* Listen announces on the local transport address. * Listen announces on the local transport address.
* *
* ```ts
* const listener = Deno.listen({ path: "/foo/bar.sock", transport: "unix" }) * const listener = Deno.listen({ path: "/foo/bar.sock", transport: "unix" })
* ```
* *
* Requires `allow-read` and `allow-write` permission. */ * Requires `allow-read` and `allow-write` permission. */
export function listen( export function listen(
@ -975,6 +1021,7 @@ declare namespace Deno {
* *
* Listen announces on the local transport address. * Listen announces on the local transport address.
* *
* ```ts
* const listener1 = Deno.listenDatagram({ * const listener1 = Deno.listenDatagram({
* port: 80, * port: 80,
* transport: "udp" * transport: "udp"
@ -984,6 +1031,7 @@ declare namespace Deno {
* port: 80, * port: 80,
* transport: "udp" * transport: "udp"
* }); * });
* ```
* *
* Requires `allow-net` permission. */ * Requires `allow-net` permission. */
export function listenDatagram( export function listenDatagram(
@ -994,10 +1042,12 @@ declare namespace Deno {
* *
* Listen announces on the local transport address. * Listen announces on the local transport address.
* *
* ```ts
* const listener = Deno.listenDatagram({ * const listener = Deno.listenDatagram({
* address: "/foo/bar.sock", * address: "/foo/bar.sock",
* transport: "unixpacket" * transport: "unixpacket"
* }); * });
* ```
* *
* Requires `allow-read` and `allow-write` permission. */ * Requires `allow-read` and `allow-write` permission. */
export function listenDatagram( export function listenDatagram(
@ -1013,11 +1063,13 @@ declare namespace Deno {
* Connects to the hostname (default is "127.0.0.1") and port on the named * 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`). * transport (default is "tcp"), and resolves to the connection (`Conn`).
* *
* ```ts
* const conn1 = await Deno.connect({ port: 80 }); * const conn1 = await Deno.connect({ port: 80 });
* const conn2 = await Deno.connect({ hostname: "192.0.2.1", 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 conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
* const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" }); * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
* const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" }); * const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
* ```
* *
* Requires `allow-net` permission for "tcp" and `allow-read` for unix. */ * Requires `allow-net` permission for "tcp" and `allow-read` for unix. */
export function connect( export function connect(
@ -1041,8 +1093,10 @@ declare namespace Deno {
* Using this function requires that the other end of the connection is * Using this function requires that the other end of the connection is
* prepared for TLS handshake. * prepared for TLS handshake.
* *
* ```ts
* const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" }); * const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
* const tlsConn = await Deno.startTls(conn, { certFile: "./certs/my_custom_root_CA.pem", hostname: "127.0.0.1", port: 80 }); * const tlsConn = await Deno.startTls(conn, { certFile: "./certs/my_custom_root_CA.pem", hostname: "127.0.0.1", port: 80 });
* ```
* *
* Requires `allow-net` permission. * Requires `allow-net` permission.
*/ */
@ -1138,10 +1192,12 @@ declare namespace Deno {
export class Permissions { export class Permissions {
/** Resolves to the current status of a permission. /** Resolves to the current status of a permission.
* *
* ```ts
* const status = await Deno.permissions.query({ name: "read", path: "/etc" }); * const status = await Deno.permissions.query({ name: "read", path: "/etc" });
* if (status.state === "granted") { * if (status.state === "granted") {
* data = await Deno.readFile("/etc/passwd"); * data = await Deno.readFile("/etc/passwd");
* } * }
* ```
*/ */
query(desc: PermissionDescriptor): Promise<PermissionStatus>; query(desc: PermissionDescriptor): Promise<PermissionStatus>;
@ -1154,12 +1210,14 @@ declare namespace Deno {
/** Requests the permission, and resolves to the state of the permission. /** Requests the permission, and resolves to the state of the permission.
* *
* ```ts
* const status = await Deno.permissions.request({ name: "env" }); * const status = await Deno.permissions.request({ name: "env" });
* if (status.state === "granted") { * if (status.state === "granted") {
* console.log(Deno.homeDir()); * console.log(Deno.homeDir());
* } else { * } else {
* console.log("'env' permission is denied."); * console.log("'env' permission is denied.");
* } * }
* ```
*/ */
request(desc: PermissionDescriptor): Promise<PermissionStatus>; request(desc: PermissionDescriptor): Promise<PermissionStatus>;
} }
@ -1177,7 +1235,9 @@ declare namespace Deno {
/** Get the `hostname` of the machine the Deno process is running on. /** Get the `hostname` of the machine the Deno process is running on.
* *
* ```ts
* console.log(Deno.hostname()); * console.log(Deno.hostname());
* ```
* *
* Requires `allow-env` permission. * Requires `allow-env` permission.
*/ */