How to Write a File in Deno: Simple Guide with Examples
Deno.writeTextFile or Deno.writeFile functions. These functions take the file path and content as arguments and return a promise that resolves when writing is complete. You must run your script with --allow-write permission to write files.Syntax
The main function to write text to a file in Deno is Deno.writeTextFile(path, data). Here, path is the file location as a string, and data is the text content you want to save. This function returns a promise, so you use await to wait for it to finish.
For binary data, use Deno.writeFile(path, data) where data is a Uint8Array.
Remember to run your script with --allow-write permission to allow file writing.
await Deno.writeTextFile("example.txt", "Hello from Deno!");
Example
This example writes the string "Hello, Deno!" to a file named greeting.txt. It uses await to ensure the file is written before the program ends.
const filename = "greeting.txt"; const content = "Hello, Deno!"; await Deno.writeTextFile(filename, content); console.log(`File '${filename}' written successfully.`);
Common Pitfalls
- Missing write permission: Running the script without
--allow-writewill cause a permission error. - Not awaiting the write: Forgetting
awaitcan cause the program to exit before the file is written. - Wrong data type: Passing non-string data to
Deno.writeTextFilewill cause errors; useDeno.writeFilefor binary data.
/* Wrong: Missing await */ Deno.writeTextFile("file.txt", "data"); /* Right: Using await */ await Deno.writeTextFile("file.txt", "data");
Quick Reference
Use Deno.writeTextFile(path, text) for writing text files and Deno.writeFile(path, bytes) for binary files. Always run with --allow-write permission. Use await to ensure the write completes before continuing.