![](/img/trans.png)
[英]How can I access file handler to run flush method in deno log module using Typescript
[英]How can one check if a file or directory exists using Deno?
Deno API 自 Deno 1.0.0
发布以来发生了变化。 如果找不到文件,则引发的异常是Deno.errors.NotFound
const exists = async (filename: string): Promise<boolean> => {
try {
await Deno.stat(filename);
// successful, file or directory must exist
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// file or directory does not exist
return false;
} else {
// unexpected error, maybe permissions, pass it along
throw error;
}
}
};
exists("test.ts").then(result =>
console.log("does it exist?", result)); // true
exists("not-exist").then(result =>
console.log("does it exist?", result)); // false
由于原始答案帐户已暂停并且如果我对其发表评论无法更改他的答案,我正在重新发布一个固定的代码片段。
这里有标准库实现: https ://deno.land/std/fs/mod.ts
import {existsSync} from "https://deno.land/std/fs/mod.ts";
const pathFound = existsSync(filePath)
console.log(pathFound)
如果路径存在,则此代码将打印true
,否则将打印false
。
这是异步实现:
import {exists} from "https://deno.land/std/fs/mod.ts"
exists(filePath).then((result : boolean) => console.log(result))
确保使用不稳定标志运行 deno 并授予对该文件的访问权限:
deno run --unstable --allow-read={filePath} index.ts
没有专门用于检查文件或目录是否存在的函数,但是通过检查 Deno.ErrorKind.NotFound 的潜在错误,可以将返回有关路径的元数据的Deno.stat
函数Deno.ErrorKind.NotFound
此目的。
const exists = async (filename: string): Promise<boolean> => {
try {
await Deno.stat(filename);
// successful, file or directory must exist
return true;
} catch (error) {
if (error && error.kind === Deno.ErrorKind.NotFound) {
// file or directory does not exist
return false;
} else {
// unexpected error, maybe permissions, pass it along
throw error;
}
}
};
exists("test.ts").then(result =>
console.log("does it exist?", result)); // true
exists("not-exist").then(result =>
console.log("does it exist?", result)); // false
exists
函数实际上是 std/fs 模块的一部分,尽管它目前被标记为不稳定。 这意味着您需要deno run --unstable
: https ://deno.land/std/fs/README.md#exists
由于潜在的竞争条件,Deno 的 exists() 方法已被弃用,并引用了“使用时间检查时间”漏洞。
他们建议您直接执行操作并查找错误。 此方法使用新建议实现了副本 exists():
async function exists(file: string) {
try {
await Deno.stat(file);
}
catch(e) {
if(e instanceof Deno.errors.NotFound) {
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.