Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
⌘K
Up or down tonavigateEnter toselectEscape toclose
On this page

Web Platform APIs

One way Deno simplifies web and cloud development is by using standard WebPlatform APIs (likefetch, WebSockets and more) over proprietary APIs. Thismeans if you've ever built for the browser, you're likely already familiar withDeno, and if you're learning Deno, you're also investing in your knowledge ofthe web.

Explore supported Web APIs

Below we'll highlight some of the standard Web APIs that Deno supports.

To check if a Web Platform API is available in Deno, you can click onthe interface on MDNand refer toits Browser Compatibility table.

fetchJump to heading

Thefetch API can be used to make HTTP requests. It isimplemented as specified in theWHATWGfetch spec.

Spec deviationsJump to heading

  • The Deno user agent does not have a cookie jar. As such, theset-cookieheader on a response is not processed, or filtered from the visible responseheaders.
  • Deno does not follow the same-origin policy, because the Deno user agentcurrently does not have the concept of origins, and it does not have a cookiejar. This means Deno does not need to protect against leaking authenticateddata cross origin. Because of this Deno does not implement the followingsections of the WHATWGfetch specification:
    • Section3.1. 'Origin' header.
    • Section3.2. CORS protocol.
    • Section3.5. CORB.
    • Section3.6. 'Cross-Origin-Resource-Policy' header.
    • Atomic HTTP redirect handling.
    • Theopaqueredirect response type.
  • Afetch with aredirect mode ofmanual will return abasic responserather than anopaqueredirect response.
  • The specification is vague on howfile: URLs are to be handled.Firefox is the only mainstream browser that implements fetchingfile: URLs,and even then it doesn't work by default. As of Deno 1.16, Deno supportsfetching local files. See the next section for details.
  • Therequest andresponse header guards are implemented, but unlikebrowsers do not have any constraints on which header names are allowed.
  • Thereferrer,referrerPolicy,mode,credentials,cache,integrity,keepalive, andwindow properties and their relevant behaviours inRequestInit are not implemented. The relevant fields are not present on theRequest object.
  • Request body upload streaming is supported (on HTTP/1.1 and HTTP/2). Unlikethe current fetch proposal, the implementation supports duplex streaming.
  • Theset-cookie header is not concatenated when iterated over in theheaders iterator. This behaviour is in theprocess of being specified.

Fetching local filesJump to heading

Deno supports fetchingfile: URLs. This makes it easier to write code thatuses the same code path on a server as local, as well as easier to author codethat works both with the Deno CLI and Deno Deploy.

Deno only supports absolute file URLs, this means thatfetch("./some.json")will not work. It should be noted though that if--location isspecified, relative URLs use the--location as the base, but afile: URLcannot be passed as the--location.

To be able to fetch a resource, relative to the current module, which would workif the module is local or remote, you should to useimport.meta.url as thebase. For example:

const response=awaitfetch(newURL("./config.json",import.meta.url));const config=await response.json();

Notes on fetching local files:

  • Permissions are applied to reading resources, so an appropriate--allow-readpermission is needed to be able to read a local file.
  • Fetching locally only supports theGET method, and will reject the promisewith any other method.
  • A file that does not exist simply rejects the promise with a vagueTypeError. This is to avoid the potential of fingerprinting attacks.
  • No headers are set on the response. Therefore it is up to the consumer todetermine things like the content type or content length.
  • Response bodies are streamed from the Rust side, so large files are availablein chunks, and can be cancelled.

CustomEvent and EventTargetJump to heading

TheDOM Event API can be used to dispatch and listen toevents happening in an application. It is implemented as specified in theWHATWG DOM spec.

Spec deviationsJump to heading

  • Events do not bubble, because Deno does not have a DOM hierarchy, so there isno tree for Events to bubble/capture through.
  • timeStamp property is always set to0.

TypingsJump to heading

The TypeScript definitions for the implemented web APIs can be found in thelib.deno.shared_globals.d.tsandlib.deno.window.d.tsfiles.

Definitions that are specific to workers can be found in thelib.deno.worker.d.tsfile.

LocationJump to heading

Deno supports thelocation global from the web.

Location flagJump to heading

There is no "web page" whose URL we can use for a location in a Deno process. Weinstead allow users to emulate a document location by specifying one on the CLIusing the--location flag. It can be ahttp orhttps URL.

// deno run --location https://example.com/path main.tsconsole.log(location.href);// "https://example.com/path"

You must pass--location <href> for this to work. If you don't, any access tothelocation global will throw an error.

// deno run main.tsconsole.log(location.href);// error: Uncaught ReferenceError: Access to "location", run again with --location <href>.

Settinglocation or any of its fields will normally cause navigation inbrowsers. This is not applicable in Deno, so it will throw in this situation.

// deno run --location https://example.com/path main.tslocation.pathname="./foo";// error: Uncaught NotSupportedError: Cannot set "location.pathname".

Extended usageJump to heading

On the web, resource resolution (excluding modules) typically uses the value oflocation.href as the root on which to base any relative URLs. This affectssome web APIs adopted by Deno.

Fetch APIJump to heading

// deno run --location https://api.github.com/ --allow-net main.tsconst response=awaitfetch("./orgs/denoland");// Fetches "https://api.github.com/orgs/denoland".

Thefetch() call above would throw if the--location flag was not passed,since there is no web-analogous location to base it onto.

Worker modulesJump to heading

// deno run --location https://example.com/index.html --allow-net main.tsconst worker=newWorker("./workers/hello.ts",{ type:"module"});// Fetches worker module at "https://example.com/workers/hello.ts".

Note

For the above use cases, it is preferable to pass URLs in full rather thanrelying on--location. You can manually base a relative URL using theURLconstructor if needed.

The--location flag is intended for those who have a specific purpose in mindfor emulating a document location and are aware that this will only work atapplication-level. However, you may also use it to silence errors from adependency which is frivolously accessing thelocation global.

Web StorageJump to heading

TheWeb Storage API provides an API for storing string keysand values. Persisting data works similar to a browser, and has a 10MB storagelimit. The globalsessionStorage object only persists data for the currentexecution context, whilelocalStorage persists data from execution toexecution.

In a browser,localStorage persists data uniquely per origin (effectively theprotocol plus hostname plus port). As of Deno 1.16, Deno has a set of rules todetermine what is a unique storage location:

  • When using the--location flag, the origin for the location is used touniquely store the data. That means a location ofhttp://example.com/a.tsandhttp://example.com/b.ts andhttp://example.com:80/ would all share thesame storage, buthttps://example.com/ would be different.
  • If there is no location specifier, but there is a--config configurationfile specified, the absolute path to that configuration file is used. Thatmeansdeno run --config deno.jsonc a.ts anddeno run --config deno.jsonc b.ts would share the same storage, butdeno run --config tsconfig.json a.ts would be different.
  • If there is no configuration or location specifier, Deno uses the absolutepath to the main module to determine what storage is shared. The Deno REPLgenerates a "synthetic" main module that is based off the current workingdirectory wheredeno is started from. This means that multiple invocationsof the REPL from the same path will share the persistedlocalStorage data.

To set, get and remove items fromlocalStorage, you can use the following:

// Set an item in localStoragelocalStorage.setItem("myDemo","Deno App");// Read an item from localStorageconst cat= localStorage.getItem("myDemo");// Remove an item from localStoragelocalStorage.removeItem("myDemo");// Remove all items from localStoragelocalStorage.clear();

Web WorkersJump to heading

Deno supports theWeb Worker API.

Workers can be used to run code on multiple threads. Each instance ofWorkeris run on a separate thread, dedicated only to that worker.

Currently Deno supports onlymodule type workers; thus it's essential to passthetype: "module" option when creating a new worker.

Use of relative module specifiers in the main worker are only supported with--location <href> passed on the CLI. This is not recommended for portability.You can instead use theURL constructor andimport.meta.url to easily createa specifier for some nearby script. Dedicated workers, however, have a locationand this capability by default.

// GoodnewWorker(import.meta.resolve("./worker.js"),{ type:"module"});// BadnewWorker(import.meta.resolve("./worker.js"));newWorker(import.meta.resolve("./worker.js"),{ type:"classic"});newWorker("./worker.js",{ type:"module"});

As with regular modules, you can use top-levelawait in worker modules.However, you should be careful to always register the message handler before thefirstawait, since messages can be lost otherwise. This is not a bug in Deno,it's just an unfortunate interaction of features, and it also happens in allbrowsers that support module workers.

import{ delay}from"jsr:@std/async@1/delay";// First await: waits for a second, then continues running the module.awaitdelay(1000);// The message handler is only set after that 1s delay, so some of the messages// that reached the worker during that second might have been fired when no// handler was registered.self.onmessage=(evt)=>{console.log(evt.data);};

Instantiation permissionsJump to heading

Creating a newWorker instance is similar to a dynamic import; therefore Denorequires appropriate permission for this action.

For workers using local modules;--allow-read permission is required:

main.ts
newWorker(import.meta.resolve("./worker.ts"),{ type:"module"});
worker.ts
console.log("hello world");self.close();
$ deno run main.tserror: Uncaught PermissionDenied:read access to"./worker.ts", run again with the --allow-read flag$ deno run --allow-read main.tshello world

For workers using remote modules;--allow-net permission is required:

main.ts
newWorker("https://example.com/worker.ts",{ type:"module"});
worker.ts
// This file is hosted at https://example.com/worker.tsconsole.log("hello world");self.close();
$ deno run main.tserror: Uncaught PermissionDenied: net access to"https://example.com/worker.ts", run again with the --allow-net flag$ deno run --allow-net main.tshello world

Using Deno in a workerJump to heading

main.js
const worker=newWorker(import.meta.resolve("./worker.js"),{type:"module",});worker.postMessage({filename:"./log.txt"});
worker.js
self.onmessage=async(e)=>{const{ filename}= e.data;const text=await Deno.readTextFile(filename);  console.log(text);  self.close();};
log.txt
hello world
$ deno run --allow-read main.jshello world

Specifying worker permissionsJump to heading

Caution

This is an unstable Deno feature. Learn more aboutunstable features.

The permissions available for the worker are analogous to the CLI permissionflags, meaning every permission enabled there can be disabled at the level ofthe Worker API. You can find a more detailed description of each of thepermission optionshere.

By default a worker will inherit permissions from the thread it was created in,however in order to allow users to limit the access of this worker we providethedeno.permissions option in the worker API.

For permissions that support granular access you can pass in a list of thedesired resources the worker will have access to, and for those who only havethe on/off option you can pass true/false respectively:

const worker=newWorker(import.meta.resolve("./worker.js"),{  type:"module",  deno:{    permissions:{      net:["deno.land",],      read:[newURL("./file_1.txt",import.meta.url),newURL("./file_2.txt",import.meta.url),],      write:false,},},});

Granular access permissions receive both absolute and relative routes asarguments, however take into account that relative routes will be resolvedrelative to the file the worker is instantiated in, not the path the worker fileis currently in:

const worker=newWorker(newURL("./worker/worker.js",import.meta.url).href,{    type:"module",    deno:{      permissions:{        read:["/home/user/Documents/deno/worker/file_1.txt","./worker/file_2.txt",],},},},);

Bothdeno.permissions and its children support the option"inherit", whichimplies it will borrow its parent permissions:

// This worker will inherit its parent permissionsconst worker=newWorker(import.meta.resolve("./worker.js"),{  type:"module",  deno:{    permissions:"inherit",},});
// This worker will inherit only the net permissions of its parentconst worker=newWorker(import.meta.resolve("./worker.js"),{  type:"module",  deno:{    permissions:{      env:false,      hrtime:false,      net:"inherit",      ffi:false,      read:false,      run:false,      write:false,},},});

Not specifying thedeno.permissions option or one of its children will causethe worker to inherit by default:

// This worker will inherit its parent permissionsconst worker=newWorker(import.meta.resolve("./worker.js"),{  type:"module",});
// This worker will inherit all the permissions of its parent BUT netconst worker=newWorker(import.meta.resolve("./worker.js"),{  type:"module",  deno:{    permissions:{      net:false,},},});

You can disable the permissions of the worker all together by passing"none"to thedeno.permissions option:

// This worker will not have any permissions enabledconst worker=newWorker(import.meta.resolve("./worker.js"),{  type:"module",  deno:{    permissions:"none",},});

Deviations of other APIs from specJump to heading

Cache APIJump to heading

Only the following APIs are implemented:

A few things that are different compared to browsers:

  1. You cannot pass relative paths to the APIs. The request can be an instance ofRequest or URL or a url string.
  2. match() &delete() don't support query options yet.

Did you find what you needed?

What can we do to improve this page?

If provided, you'll be @mentioned in the created GitHub issue

Privacy policy

[8]ページ先頭

©2009-2025 Movatter.jp