Deno中使用readFile读取URL报错,求正确实现方法
解决Deno从URL读取文件的问题
你的代码出错是因为 Deno.readFile() 仅支持读取本地文件路径,无法直接传入URL来远程获取文件。要实现从URL读取文件,需要用HTTP请求的方式,比如使用Deno支持的标准fetch API。
修改后的代码示例
方式1:直接获取文本(更简洁)
const url = new URL("https://github.com/denoland/deno/releases/download/v1.30.3/lib.deno.d.ts"); const response = await fetch(url); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } const text = await response.text(); console.log(text);
方式2:使用TextDecoder解码(和你原代码逻辑对齐)
如果你想保留TextDecoder的使用逻辑,可以先获取响应的二进制数据再解码:
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 response = await fetch(url); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } const arrayBuffer = await response.arrayBuffer(); const text = decoder.decode(arrayBuffer); console.log(text);
运行注意事项
Deno默认限制网络访问,运行代码时需要添加--allow-net权限:
deno run --allow-net your-file.ts
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

