作者:mobiledu2502890213 | 来源:互联网 | 2022-12-07 10:21
我正在编写一个用TypeScript编写的字数统计程序,我正试图在Deno中运行.我只是在没有参数deno ./word_count.ts
的情况下调用它,所以它应该具有默认的只读文件系统访问权限.我希望,我可能能够使用标准的浏览器fetch()
API使用的file:
URL方案从文件系统读取,如下所示:
word_count.ts
const countWords = (s: string): number =>
s.split(/\s+/g).filter(w => /[a-z0-9]/.test(w)).length;
const main = async () => {
const text = await (await fetch("file:///./input.txt")).text();
const count = countWords(text);
console.log(`I read ${count} words.`);
};
main();
input.txt
The quick brown fox jumps over the lazy dog.
但是当我尝试时,我看到我发现它fetch
不支持file
URL:
Error: an error occurred trying to connect: invalid URL, scheme must be http
at FetchResponse.onMsg (deno/js/fetch.ts:121:21)
at FetchRequest.onMsg (deno/js/fetch.ts:152:19)
at onFetchRes (deno/js/fetch.ts:28:8)
at onMessage$1 (deno/js/main.ts:30:7)
如何在Deno中读取本地文件的内容?
1> 小智..:
Deno 'deno'
在其标准库中包含一个函数,该函数可在特殊的导入路径中使用Deno
.
import {readFileSync} from 'deno';
const bytes = readFileSync('./input.txt');
这将文件的内容作为字节数组读取.如果文件包含您希望作为字符串的文本(如示例中所示),则可以使用标准ECMAScript readFileSync(filename: string): Uint8Array
类(MDN文档).
const utf8Decoder = new TextDecoder('utf-8');
const string = utf8Decoder.decode(bytes);
对于原始示例,这给了我们:
'deno'
import {readFileSync} from 'deno';
const countWords = (s: string): number =>
s.split(/\s+/g).filter(w => /[a-z0-9]/.test(w)).length;
const main = async () => {
const decoder = new TextDecoder("utf-8");
const bytes = readFileSync("./input.txt");
const text = decoder.decode(bytes);
const count = countWords(text);
console.log(`I read ${count} words.`);
};
main();
这产生了所需的输出:
$ deno ./word_count.ts
I read 9 words.