by Sai gowtham

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:

app.js
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.

app.js
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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course