W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Deno 支持 Web Worker API. Worker 能夠用來(lái)在多個(gè)線(xiàn)程中運(yùn)行代碼,Worker 的每個(gè)實(shí)例都會(huì)在一個(gè)單獨(dú)的線(xiàn)程中運(yùn)行,這個(gè)線(xiàn)程專(zhuān)屬于它。 目前,Deno 只支持 module 類(lèi)型的 worker,因此在創(chuàng)建新的 worker 時(shí)必須傳遞 type: "module" 選項(xiàng)。 目前,相對(duì)模塊說(shuō)明符 (Relative module specifiers) 尚不支持。作為代替,您可以用 URL 構(gòu)造函數(shù)和 import.meta.url 來(lái)為附近的腳本創(chuàng)建說(shuō)明符。
// Good
new Worker(new URL("worker.js", import.meta.url).href, { type: "module" });
// Bad
new Worker(new URL("worker.js", import.meta.url).href);
new Worker(new URL("worker.js", import.meta.url).href, { type: "classic" });
new Worker("./worker.js", { type: "module" });
創(chuàng)建一個(gè)新的 Worker 實(shí)例的行為與動(dòng)態(tài)導(dǎo)入類(lèi)似,因此 Deno 需要適當(dāng)?shù)臋?quán)限來(lái)做這個(gè)操作。 對(duì)于使用本地模塊的 worker,Deno 需要讀取 (--allow-read) 權(quán)限:
main.ts
new Worker(new URL("worker.ts", import.meta.url).href, { type: "module" });
worker.ts
console.log("hello world");
self.close();
$ deno run main.ts
error: Uncaught PermissionDenied: read access to "./worker.ts", run again with the --allow-read flag
$ deno run --allow-read main.ts
hello world
對(duì)于使用遠(yuǎn)程模塊的 worker,Deno 需要網(wǎng)絡(luò) (--allow-net) 權(quán)限:
main.ts
new Worker("https://example.com/worker.ts", { type: "module" });
worker.ts
console.log("hello world");
self.close();
$ deno run main.ts
error: Uncaught PermissionDenied: net access to "https://example.com/worker.ts", run again with the --allow-net flag
$ deno run --allow-net main.ts
hello world
這是一個(gè)不穩(wěn)定的 Deno 特性。 更多信息請(qǐng)查閱 穩(wěn)定性 默認(rèn)情況下,Deno 命名空間在 worker 作用域中不可用。 要想啟用 Deno 命名空間,在創(chuàng)建新的 worker 時(shí)傳遞 deno: true 選項(xiàng):
const worker = new Worker(new URL("worker.js", import.meta.url).href, {
type: "module",
deno: true,
});
worker.postMessage({ filename: "./log.txt" });
self.onmessage = async (e) => {
const { filename } = e.data;
const text = await Deno.readTextFile(filename);
console.log(text);
self.close();
};
hello world
$ deno run --allow-read --unstable main.js
hello world
當(dāng) Deno 命名空間在 worker 作用域中啟用時(shí),此 worker 繼承創(chuàng)建者的權(quán)限(使用類(lèi)似 --allow-* 的選項(xiàng)指定的權(quán)限)。 我們計(jì)劃提供 worker 權(quán)限的配置方法。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: