简体   繁体   English

无法在 Deno 中加载依赖的 txt 文件

[英]Can't load txt file of dependecy in Deno

I'm making simple package that edits and provides data, saved in txt file.我正在制作简单的 package 来编辑和提供数据,并保存在 txt 文件中。
Since I can't import non-script files(JSON, txt, etc..), I'm using Deno.open() .由于我无法导入非脚本文件(JSON、txt 等),我正在使用Deno.open()

sample.txt (In package) sample.txt(包内)

Hello, World!

mod.ts (In package) mod.ts(在包中)

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()

Package runs fine alone, but make error when it is used in other directory. Package 单独运行正常,但在其他目录使用时出错。
test.ts (Local file, loads the package in different directory) test.ts(本地文件,加载 package 到不同目录)

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

console.log(file)

error:错误:

$ 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

It seems like deno downloads script files only.似乎 deno 只下载脚本文件。 (generated file image) (生成的文件图像)
I just want to make deno load non-script data files too.我也只想让 deno 加载非脚本数据文件。
How can I fix this?我怎样才能解决这个问题?

Your code works fine, it's important to check the error:您的代码工作正常,检查错误很重要:

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

It's telling you that "sample.txt" does not exist on the current directory.它告诉您当前目录中不存在"sample.txt" Make sure you're executing Deno from the directory where the file is present.确保从文件所在的目录执行 Deno。


Aside from that for reading text files you can use Deno.readTextFile instead除了读取文本文件之外,您还可以使用Deno.readTextFile

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

Your code expects sample.txt to be on your filesystem, but you're trying to read sample.txt from the github repository, the only solution would be to perform an HTTP request to fetch that file, instead of using Deno filesystem APIs.您的代码期望sample.txt在您的文件系统上,但您正尝试从 github 存储库中读取sample.txt ,唯一的解决方案是执行 HTTP 请求来获取该文件,而不是使用 Deno 文件系统 API。

But in that case, you won't be able to write to it.但在这种情况下,您将无法写入它。 For your use case, you should work with local files, so you'll need to create the file if it doesn't exist if you're going to write to it.对于您的用例,您应该使用本地文件,因此如果您要写入该文件,则需要创建该文件。

I'm making simple package that edits and provides data, saved in txt file.我正在制作简单的 package 来编辑和提供数据,并保存在 txt 文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM