I'm trying this code but it gives me an error:
const decoder = new TextDecoder("utf-8");
const url = new URL("https://github.com/denoland/deno/releases/download/v1.30.3/lib.deno.d.ts")
const text = await Deno.readFile(url);
console.log(decoder.decode(text));
I want to know how to make this work
The methods Deno.read*
are for interacting with the local file system.
To download the contents of a remote resource, you can use the web standard fetch
API — just like in a browser — and getting a textual representation of the resource content is also the same. Here's a basic example which will download the type declaration file in your question and print it to stdout
:
main.ts
:
async function fetchText(url: URL | string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error(`Response not OK (${response.status})`);
return response.text();
}
const url =
"https://github.com/denoland/deno/releases/download/v1.30.3/lib.deno.d.ts";
const text = await fetchText(url);
console.log(text);
I can run it in the terminal and redirect the output to a file called types_download
like this:
% deno --version
deno 1.30.3 (release, aarch64-apple-darwin)
v8 10.9.194.5
typescript 4.9.4
% deno run --allow-net main.ts > types_download
And then view the first 10 lines of the file:
% head --lines=10 types_download
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="deno.net" />
/** Deno provides extra properties on `import.meta`. These are included here
* to ensure that these are still available when using the Deno namespace in
* conjunction with other type libs, like `dom`.
*
By the way: this type declaration file is available directly from the Deno CLI using the deno types
command:
% deno types > types_cli
% head --lines=10 types_cli
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="deno.net" />
/** Deno provides extra properties on `import.meta`. These are included here
* to ensure that these are still available when using the Deno namespace in
* conjunction with other type libs, like `dom`.
*