0
0
DenoHow-ToBeginner ยท 3 min read

How to Write a File in Deno: Simple Guide with Examples

In Deno, you write a file using the 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.

typescript
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.

typescript
const filename = "greeting.txt";
const content = "Hello, Deno!";

await Deno.writeTextFile(filename, content);
console.log(`File '${filename}' written successfully.`);
Output
File 'greeting.txt' written successfully.
โš ๏ธ

Common Pitfalls

  • Missing write permission: Running the script without --allow-write will cause a permission error.
  • Not awaiting the write: Forgetting await can cause the program to exit before the file is written.
  • Wrong data type: Passing non-string data to Deno.writeTextFile will cause errors; use Deno.writeFile for binary data.
typescript
/* 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.

โœ…

Key Takeaways

Use Deno.writeTextFile to write text files and await its completion.
Run scripts with --allow-write permission to enable file writing.
Do not forget to await the write operation to avoid incomplete writes.
Use Deno.writeFile for binary data instead of writeTextFile.
File paths are strings and can be relative or absolute.