【问题标题】:Can't load txt file of dependecy in Deno无法在 Deno 中加载依赖的 txt 文件
【发布时间】:2020-07-16 22:58:35
【问题描述】:

我正在制作一个简单的包,可以编辑和提供数据,保存在 txt 文件中。
由于无法导入非脚本文件(JSON、txt 等),我使用的是Deno.open()。

sample.txt (In package)

Hello, World!

mod.ts (In package)

const decoder = new TextDecoder("utf-8")

const f = await Deno.open("sample.txt")
export default decoder.decode(await Deno.readAll(f)) // Hello, World!
f.close()

包单独运行正常,但在其他目录使用时出错。
test.ts(本地文件,将包加载到不同目录)

import file from "https://raw.githubusercontent.com/gnlow/deno-file-test/master/mod.ts"

console.log(file)

错误:

$ deno -V
deno 1.2.0
$ deno run --allow-read test.ts
Download https://raw.githubusercontent.com/gnlow/deno-file-test/master/mod.ts
Compile file:///var/task/__$deno$eval.ts
error: Uncaught NotFound: No such file or directory (os error 2)
    at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
    at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
    at async Object.open ($deno$/files.ts:37:15)
    at async https://raw.githubusercontent.com/gnlow/deno-file-test/master/mod.ts:3:11

似乎 deno 只下载脚本文件。 (generated file image)
我也只想让 deno 加载非脚本数据文件。
我该如何解决这个问题?

【问题讨论】:

  • 文件确定存在吗?因为我运行相同的代码没有任何问题。查看截图:imgur.com/a/hBwoxi8
  • @Atomzwieback 我的意思是:将包加载到不同的目录中。我更清楚地编辑了我的问题。

标签: javascript typescript deno


【解决方案1】:

您的代码运行良好,检查错误很重要:

error: Uncaught NotFound: No such file or directory (os error 2)

它告诉你"sample.txt" 在当前目录中不存在。确保从文件所在的目录执行 Deno。


除了读取文本文件之外,您还可以改用Deno.readTextFile

export default await Deno.readTextFile("./sample.txt") // Hello, World!

您的代码期望 sample.txt 在您的文件系统上,但您尝试从 github 存储库中读取 sample.txt,唯一的解决方案是执行 HTTP 请求来获取该文件,而不是使用 Deno 文件系统API。

但在这种情况下,您将无法对其进行写入。对于您的用例,您应该使用本地文件,因此如果您要写入该文件,则需要创建该文件。

我正在制作一个简单的包,可以编辑和提供数据,保存在 txt 文件中。

【讨论】:

  • 我想使用这个包,在其他目录。我为不明确的措辞道歉。我编辑了我的问题。
  • 显示文件结构,“sample.txt”在哪里,否则无法给你答案。
  • "mod.ts" 和 "sample.txt" 在 github repo github.com/gnlow/deno-file-test 中。 “test.ts”在我的本地文件夹中。 “test.ts”从githubraw.githubusercontent.com/gnlow/deno-file-test/master/mod.ts加载“mod.ts”
  • 好的,你无法使用 Deno.open 加载文件系统上没有的文件。
  • 检查更新的答案,您不能使用文件系统 API 写入远程文件。您的代码应该更改,我不知道您要实现什么功能,但到目前为止它没有多大意义,除非您实际上在本地创建了 sample.txt。
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2016-09-22
  • 2012-07-24
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
相关资源
最近更新 更多