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-writeflag. - Overwriting files unintentionally: By default,
Deno.writeTextFileoverwrites existing files. Use theappendoption 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
| Parameter | Description |
|---|---|
| path | String or URL of the file to write |
| data | Text content to write to the file |
| options.append | Boolean to append text instead of overwrite (default false) |
| returns | Promise 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.