0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Deno.writeTextFile to Write Text Files

Use Deno.writeTextFile to write a string to a file asynchronously in Deno. It takes the file path and the text content as arguments and returns a promise that resolves when writing is complete.
๐Ÿ“

Syntax

The Deno.writeTextFile function writes text data to a file asynchronously. It requires two main arguments: the file path as a string or URL, and the text content as a string. It returns a Promise<void> that resolves when the write operation finishes.

You can optionally pass a third argument with options like append to add text instead of overwriting.

typescript
Deno.writeTextFile(path: string | URL, data: string, options?: { append?: boolean }): Promise<void>
๐Ÿ’ป

Example

This example writes the text "Hello, Deno!" to a file named greeting.txt. If the file does not exist, it will be created. If it exists, it will be overwritten.

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

await Deno.writeTextFile(filePath, content);
console.log(`Text written to ${filePath}`);
Output
Text written to greeting.txt
โš ๏ธ

Common Pitfalls

  • Missing permissions: Deno requires explicit permission to write files. Run your script with --allow-write flag.
  • Overwriting files unintentionally: By default, Deno.writeTextFile overwrites existing files. Use the append option to add instead.
  • Incorrect path: Provide a valid relative or absolute path. Using an invalid path causes errors.
typescript
/* Wrong: Missing permission causes error */
// deno run script.ts
await Deno.writeTextFile("file.txt", "data");

/* Right: Run with permission */
// deno run --allow-write script.ts
await Deno.writeTextFile("file.txt", "data");
๐Ÿ“Š

Quick Reference

ParameterDescription
pathString or URL of the file to write
dataText content to write to the file
options.appendBoolean to append text instead of overwrite (default false)
returnsPromise that resolves when writing finishes
โœ…

Key Takeaways

Deno.writeTextFile writes text to a file asynchronously and returns a promise.
Always run your Deno script with --allow-write permission to avoid errors.
By default, writing overwrites existing files; use the append option to add text.
Provide a valid file path as a string or URL to avoid path errors.
Use await to ensure the write operation completes before continuing.