In Deno, you can check if a file or directory exists using the Deno.stat or Deno.lstat functions. These functions return a Stat object, and if the file or directory does not exist, they throw an error. Typically, we use the try...catch structure to handle this situation.
Here is a specific example:
typescriptasync function fileExists(path: string): Promise<boolean> { try { const stats = await Deno.stat(path); return true; // File or directory exists } catch (error) { if (error instanceof Deno.errors.NotFound) { return false; // File or directory does not exist } else { throw error; // Other types of errors } } } const path = "./example.txt"; fileExists(path).then(exists => { console.log(exists ? "File exists" : "File does not exist"); }).catch(error => { console.error("Error occurred:", error); });
In this example, the fileExists function attempts to retrieve the status information for the specified path. If the file or directory exists, the function returns true. If a NotFound error is thrown, it indicates the file or directory does not exist, and the function returns false. If other types of errors occur, they are thrown directly, which may require handling by the caller.
This approach is both concise and effective, clearly distinguishing between three cases: the file/directory exists, does not exist, and other errors.