How to write files in Deno
In this tutorial, we are going to learn about writing data to files with deno using fs module.
Deno has a standard fs module, that contains different types of methods to manipulate the file system.
Using the writeFileStr() method
The writeFileStr()
method asynchronously writes data to the file in deno.
Data will be in string format.
Example:
import { writeFileStr } from "https://deno.land/std/fs/mod.ts";
const writeName = await writeFileStr("./names.txt", "Gowtham");
The first argument in the writeFileStr()
method is the path of the file you need to write, the second argument is the data
you need to add to that file.
To run it, we need to give write permissions of names.txt
file to deno by using --allow-read
flag.
deno run --unstable --allow-write=./names.txt app.js
If the names.txt
file doesn’t exist in your file system, the writeFileStr()
method will create one.
Note: All the methods inside a file system module are currently unstable, so that we have used the
--unstable
flag to enable it during runtime.
Similarly, we can use the writeFileStrSync()
method to write the file synchronously.
import { writeFileStrSync } from "https://deno.land/std/fs/mod.ts";
const writeName = await writeFileStrSync("./names.txt", "Gowtham");
Note: Both methods replace the entire contents of the file with the data you passed in the second argument.