From 857d96001d63c1cb847f3f228124d69c40d267e7 Mon Sep 17 00:00:00 2001 From: Chris Knight Date: Wed, 1 Apr 2020 04:21:37 +0100 Subject: [PATCH] doc: Improve API documentation and add examples (#4548) --- cli/js/lib.deno.ns.d.ts | 380 ++++++++++++++++++++++++++++++++-------- 1 file changed, 303 insertions(+), 77 deletions(-) diff --git a/cli/js/lib.deno.ns.d.ts b/cli/js/lib.deno.ns.d.ts index b195116d93..ef1a820604 100644 --- a/cli/js/lib.deno.ns.d.ts +++ b/cli/js/lib.deno.ns.d.ts @@ -24,15 +24,70 @@ declare namespace Deno { /** 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, or explicitly - * when `Deno.runTests` is used */ + * when `Deno.runTests` is used. `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 === "win" + * 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") + * } + * }); + */ export function test(t: TestDefinition): void; + /** 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, or explicitly - * when `Deno.runTests` is used */ + * when `Deno.runTests` is used + * + * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; + * + * Deno.test(function myTestFunction():void { + * assertEquals("hello", "hello"); + * }); + * + * Deno.test(async function myAsyncTestFunction():Promise { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world") + * }); + **/ export function test(fn: TestFunction): void; + /** 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, or explicitly - * when `Deno.runTests` is used */ + * when `Deno.runTests` is used + * + * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; + * + * Deno.test("My test description", ():void => { + * assertEquals("hello", "hello"); + * }); + * + * Deno.test("My async test description", async ():Promise => { + * const decoder = new TextDecoder("utf-8"); + * const data = await Deno.readFile("hello_world.txt"); + * assertEquals(decoder.decode(data), "Hello world") + * }); + * */ export function test(name: string, fn: TestFunction): void; enum TestStatus { @@ -118,8 +173,24 @@ declare namespace Deno { reporter?: TestReporter; } - /** Run any tests which have been registered. Always resolves - * asynchronously. */ + /** Run any tests which have been registered via `Deno.test()`. Always resolves + * asynchronously. + * + * //Register test + * Deno.test({ + * name: "example test", + * fn(): void { + * assertEquals("world", "world"); + * assertEquals({ hello: "world" }, { hello: "world" }); + * }, + * }); + * + * //Run tests + * const runInfo = await Deno.runTests(); + * console.log(runInfo.duration); // all tests duration, e.g. "5" (in ms) + * console.log(runInfo.stats.passed); //e.g. 1 + * console.log(runInfo.results[0].name); //e.g. "example test" + */ export function runTests( opts?: RunTestsOptions ): Promise<{ @@ -395,10 +466,17 @@ declare namespace Deno { export function chdir(directory: string): void; /** - * **UNSTABLE**: New API. Maybe needs permissions. + * **UNSTABLE**: New API, yet to be vetted. This API is under consideration to + * determine if permissions are required to call it. * - * If `mask` is provided, sets the process umask. Always returns what the umask - * was before the call. + * Retrieve the process umask. If `mask` is provided, sets the process umask. + * This call always returns what the umask was before the call. + * + * console.log(Deno.umask()); //e.g. 18 (0o022) + * const prevUmaskValue = Deno.umask(0o077); //e.g. 18 (0o022) + * console.log(Deno.umask()); //e.g. 63 (0o077) + * + * NOTE: This API is not implemented on Windows */ export function umask(mask?: number): number; @@ -540,7 +618,7 @@ declare namespace Deno { */ export function copy(dst: Writer, src: Reader): Promise; - /** Turns `r` into async iterator. + /** Turns a Reader, `r`, into an async iterator. * * for await (const chunk of toAsyncIterator(reader)) { * console.log(chunk); @@ -626,6 +704,7 @@ declare namespace Deno { * 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); */ export function readSync(rid: number, p: Uint8Array): number | EOF; @@ -635,39 +714,59 @@ declare namespace Deno { * File (`Symbol(EOF)`) if there was nothing to read. * * // 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" + * 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); */ export function read(rid: number, p: Uint8Array): Promise; - /** Synchronously write to the resource ID the contents of the array buffer. + /** Synchronously write to the resource ID (`rid`) the contents of the array buffer. * - * Resolves to the number of bytes written. + * Returns the number of bytes written. * * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world\n"); + * const data = encoder.encode("Hello world"); * const file = Deno.openSync("/foo/bar.txt"); - * Deno.writeSync(file.rid, data); + * const bytesWritten = Deno.writeSync(file.rid, data); // 11 + * Deno.close(file.rid); */ export function writeSync(rid: number, p: Uint8Array): number; - /** Write to the resource ID the contents of the array buffer. + /** Write to the resource ID (`rid`) the contents of the array buffer. * * Resolves to the number of bytes written. * * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world\n"); + * const data = encoder.encode("Hello world"); * const file = await Deno.open("/foo/bar.txt"); - * await Deno.write(file.rid, data); + * const bytesWritten = await Deno.write(file.rid, data); // 11 + * Deno.close(file.rid); */ export function write(rid: number, p: Uint8Array): Promise; - /** Synchronously seek a file ID to the given offset under mode given by `whence`. + /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode + * given by `whence`. The current position within the resource is returned. * - * const file = Deno.openSync("/foo/bar.txt"); - * Deno.seekSync(file.rid, 0, 0); + * 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.SEEK_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: + * //Seek 6 bytes from the start of the file + * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.SEEK_START)); //"6" + * //Seek 2 more bytes from the current position + * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.SEEK_CURRENT)); //"8" + * //Seek backwards 2 bytes from the end of the file + * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.SEEK_END)); //"9" (e.g. 11-2) */ export function seekSync( rid: number, @@ -675,10 +774,27 @@ declare namespace Deno { whence: SeekMode ): number; - /** Seek a file ID 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 current position within the resource. * - * const file = await Deno.open("/foo/bar.txt"); - * await Deno.seek(file.rid, 0, 0); + * 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.SEEK_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: + * //Seek 6 bytes from the start of the file + * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.SEEK_START)); //"6" + * //Seek 2 more bytes from the current position + * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.SEEK_CURRENT)); //"8" + * //Seek backwards 2 bytes from the end of the file + * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.SEEK_END)); //"9" (e.g. 11-2) */ export function seek( rid: number, @@ -789,7 +905,14 @@ declare namespace Deno { /** **UNSTABLE**: new API, yet to be vetted * - * Set TTY to be under raw mode or not. */ + * Set TTY to be under raw mode or not. In raw mode, characters are read and + * returned as is, without being processed. All special processing of + * characters by the terminal is disabled, including echoing input characters. + * Reading from a TTY device in raw mode is faster than reading from a TTY + * device in canonical mode. + * + * Deno.setRaw(myTTY.rid, true); + */ export function setRaw(rid: number, mode: boolean): void; /** A variable-sized buffer of bytes with `read()` and `write()` methods. @@ -868,6 +991,7 @@ declare namespace Deno { * //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); @@ -896,10 +1020,45 @@ declare namespace Deno { */ export function readAllSync(r: SyncReader): Uint8Array; - /** Write all the content of `arr` to `w`. */ + /** 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 + */ export function writeAll(w: Writer, arr: Uint8Array): Promise; - /** Synchronously write all the content of `arr` to `w`. */ + /** 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 + */ export function writeAllSync(w: SyncWriter, arr: Uint8Array): void; export interface MkdirOptions { @@ -1105,9 +1264,9 @@ declare namespace Deno { /** **UNSTABLE**: needs investigation into high precision time. * - * Synchronously changes the access and modification times of a file system - * object referenced by `path`. Given times are either in seconds (UNIX epoch - * time) or as `Date` objects. + * Synchronously changes the access (`atime`) and modification (`mtime`) times + * of a file system object referenced by `path`. Given times are either in + * seconds (UNIX epoch time) or as `Date` objects. * * Deno.utimeSync("myfile.txt", 1556495550, new Date()); * @@ -1120,9 +1279,9 @@ declare namespace Deno { /** **UNSTABLE**: needs investigation into high precision time. * - * Changes the access and modification times of a file system object - * referenced by `path`. Given times are either in seconds (UNIX epoch time) - * or as `Date` objects. + * Changes the access (`atime`) and modification (`mtime`) times of a file + * system object referenced by `path`. Given times are either in seconds + * (UNIX epoch time) or as `Date` objects. * * await Deno.utime("myfile.txt", 1556495550, new Date()); * @@ -1139,40 +1298,51 @@ declare namespace Deno { recursive?: boolean; } - /** Synchronously removes the named file or directory. Throws error if - * permission denied, path not found, or path is a non-empty directory and - * the `recursive` option isn't set to `true`. + /** Synchronously removes the named file or directory. * - * Deno.removeSync("/path/to/dir/or/file", { recursive: false }); + * 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. */ export function removeSync(path: string, options?: RemoveOptions): void; - /** Removes the named file or directory. Throws error if permission denied, - * path not found, or path is a non-empty directory and the `recursive` - * option isn't set to `true`. + /** Removes the named file or directory. * - * await Deno.remove("/path/to/dir/or/file", { recursive: false }); + * 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. */ export function remove(path: string, options?: RemoveOptions): Promise; - /** Synchronously renames (moves) `oldpath` to `newpath`. 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. + /** 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"); * + * Throws error if attempting to rename to a directory which exists and is not + * empty. + * * Requires `allow-read` and `allow-write` permissions. */ export function renameSync(oldpath: string, newpath: string): void; - /** Renames (moves) `oldpath` to `newpath`. 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. + /** 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"); * + * Throws error if attempting to rename to a directory which exists and is not + * empty. + * * Requires `allow-read` and `allow-write`. */ export function rename(oldpath: string, newpath: string): Promise; @@ -1266,16 +1436,26 @@ declare namespace Deno { isSymlink(): boolean; } - /** Returns absolute normalized path with, symbolic links resolved. + /** Returns absolute normalized path, with symbolic links resolved. * - * const realPath = Deno.realpathSync("./some/path"); + * // 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. */ export function realpathSync(path: string): string; /** Resolves to the absolute normalized path, with symbolic links resolved. * - * const realPath = await Deno.realpath("./some/path"); + * // 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. */ export function realpath(path: string): Promise; @@ -1397,9 +1577,12 @@ declare namespace Deno { /** **UNSTABLE**: `type` argument type may be changed to `"dir" | "file"`. * - * Creates `newpath` as a symbolic link to `oldpath`. The type argument can be - * set to `dir` or `file`. Is only available on Windows and ignored on other - * platforms. + * Creates `newpath` as a symbolic link to `oldpath`. + * + * The type argument can be set to `dir` or `file`. This argument is only + * available on Windows and ignored on other platforms. + * + * NOTE: This function is not yet implemented on Windows. * * Deno.symlinkSync("old/name", "new/name"); * @@ -1410,11 +1593,14 @@ declare namespace Deno { type?: string ): void; - /** **UNSTABLE**: `type` argument may be changed to "dir" | "file" + /** **UNSTABLE**: `type` argument may be changed to `"dir" | "file"` * - * Creates `newpath` as a symbolic link to `oldpath`. The type argument can be - * set to `dir` or `file`. Is only available on Windows and ignored on other - * platforms. + * Creates `newpath` as a symbolic link to `oldpath`. + * + * The type argument can be set to `dir` or `file`. This argument is only + * available on Windows and ignored on other platforms. + * + * NOTE: This function is not yet implemented on Windows. * * await Deno.symlink("old/name", "new/name"); * @@ -1437,14 +1623,18 @@ declare namespace Deno { mode?: number; } - /** 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. * * const encoder = new TextEncoder(); * const data = encoder.encode("Hello world\n"); - * Deno.writeFileSync("hello.txt", data); + * Deno.writeFileSync("hello1.txt", data); //overwrite "hello.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 create is `false`. + * Requires `allow-write` permission, and `allow-read` if `options.create` is + * `false`. */ export function writeFileSync( path: string, @@ -1452,14 +1642,17 @@ declare namespace Deno { options?: WriteFileOptions ): void; - /** 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. * * const encoder = new TextEncoder(); * const data = encoder.encode("Hello world\n"); - * await Deno.writeFile("hello.txt", data); + * await Deno.writeFile("hello1.txt", data); //overwrite "hello.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 create is `false`. + * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`. */ export function writeFile( path: string, @@ -1620,16 +1813,34 @@ declare namespace Deno { } /** Synchronously truncates or extends the specified file, to reach the - * specified `len`. + * specified `len`. If `len` is not specified then the entire file contents + * are truncated. * - * Deno.truncateSync("hello.txt", 10); + * //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. */ export function truncateSync(name: string, len?: number): void; - /** Truncates or extends the specified file, to reach the specified `len`. + /** Truncates or extends the specified file, to reach the specified `len`. If + * `len` is not specified then the entire file contents are truncated. * - * await Deno.truncate("hello.txt", 10); + * //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. */ export function truncate(name: string, len?: number): Promise; @@ -1686,8 +1897,8 @@ declare namespace Deno { ReadWrite, // TODO(ry) panics on ReadWrite. } - /** **UNSTABLE**: Maybe should remove `how` parameter maybe remove - * `ShutdownMode` entirely. + /** **UNSTABLE**: Both the `how` parameter and `ShutdownMode` enum are under + * consideration for removal. * * Shutdown socket send and receive operations. * @@ -1919,10 +2130,15 @@ declare namespace Deno { [rid: number]: string; } - /** **UNSTABLE**: reconsider return type. + /** **UNSTABLE**: The return type is under consideration and may change. * - * Returns a map of open _file like_ resource ids along with their string - * representations. */ + * Returns a map of open _file like_ resource ids (rid) along with their string + * representations. + * + * console.log(Deno.resources()); //e.g. { 0: "stdin", 1: "stdout", 2: "stderr" } + * Deno.openSync('../test.file'); + * console.log(Deno.resources()); //e.g. { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" } + */ export function resources(): ResourceMap; /** **UNSTABLE**: new API. Needs docs. */ @@ -2032,7 +2248,8 @@ declare namespace Deno { stdin?: ProcessStdio | number; } - /** Spawns new subprocess. + /** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`, + * an array of program arguments, the first of which is the binary. * * Subprocess uses same working directory as parent process unless `opt.cwd` * is specified. @@ -2044,6 +2261,12 @@ declare namespace Deno { * `opt.stdout`, `opt.stderr` and `opt.stdin` can be specified independently - * they can be set to either `ProcessStdio` or `rid` of open file. * + * Details of the spawned process are returned. + * + * const p = Deno.run({ + * cmd: ["echo", "hello"], + * }); + * * Requires `allow-run` permission. */ export function run(opt: RunOptions): Process; @@ -2612,7 +2835,10 @@ declare namespace Deno { * } * * The above for-await loop exits after 5 seconds when `sig.dispose()` is - * called. */ + * called. + * + * NOTE: This functionality is not yet implemented on Windows. + */ export function signal(signo: number): SignalStream; /** **UNSTABLE**: new API, yet to be vetted. */