Create file if it doesn't exist, fail otherwise #12903
-
In my application, I need to create a file if it doesn't exist but if the file already exist this should trigger some special handling. This can be done synchronously:
However, as my applications handles many requests asynchronously and writing such files is a frequent, writing the files synchronously isn't satisfactory. Using the async Is there a way to asynchronously write a file only if it doesn't yet exist? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
@retog your solution is quite racy. You can do that using import { writeAll } from "https://deno.land/std/streams/conversion.ts";
const file = await Deno.open(filename, { createNew: true, write: true });
await writeAll(file, content)
Deno.close(file.rid);
See https://doc.deno.land/builtin/stable#Deno.OpenOptions for more details. |
Beta Was this translation helpful? Give feedback.
@retog your solution is quite racy. You can do that using
Deno.open()
API and specifying relevant options:createNew
option ensures that no file exists at specified location, otherwise it will throw an error.See https://doc.deno.land/builtin/stable#Deno.OpenOptions for more details.