From 76ac5a25addecde9ed13f8bfd2a800a2b97dd49a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 8 Apr 2026 08:35:41 +0200 Subject: [PATCH] docs: simplify file existence example to use node:fs Rewrite the checking_file_existence example to use the Node.js-compatible `fs.exists` and `fs/promises.access` APIs instead of Deno-specific APIs. Closes #2987 Co-Authored-By: Claude Opus 4.6 (1M context) --- examples/scripts/checking_file_existence.ts | 31 ++++++++------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/examples/scripts/checking_file_existence.ts b/examples/scripts/checking_file_existence.ts index ec22e80fd..899d1ebb3 100644 --- a/examples/scripts/checking_file_existence.ts +++ b/examples/scripts/checking_file_existence.ts @@ -2,33 +2,26 @@ * @title Checking for file existence * @difficulty beginner * @tags cli, deploy - * @run -R -W + * @run -R * @group File System * * When creating files it can be useful to first ensure that * such a file doesn't already exist. - * There are a number of ways to do this. */ -// Use the `exists` utility from the std library to check for existence of a file or folder. -// Note: Can create a race condition if followed by file operation. -// Consider the alternative below. -import { exists } from "jsr:@std/fs/exists"; -await exists("./this_file_or_folder_exists"); // true -await exists("./this_file_or_folder_does_not_exist"); // false +// Use the Node.js-compatible `fs.exists` function for a simple check. +import { exists } from "node:fs"; -// We can also use this function to check if the item on a path is a file or a directory -await exists("./file", { isFile: true }); // true -await exists("./directory", { isFile: true }); // false +exists("./example.txt", (fileExists) => { + console.log(fileExists); // true or false +}); + +// For a promise-based approach, use `access` from `node:fs/promises`. +import { access } from "node:fs/promises"; -// Do not use the above function if performing a check directly before another operation on that file. -// Doing so creates a race condition. The `exists` function is not recommended for that usecase. -// Consider this alternative which checks for existence of a file without doing any other filesystem operations. try { - const stats = await Deno.lstat("example.txt"); -} catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } + await access("./example.txt"); + console.log("File exists"); +} catch { console.log("File does not exist"); }