by Sai gowtham

How to read a file in Deno

In this tutorial, we are going to learn about how to read the contents of a file into memory and output as a string in deno using fs module.

Deno provides us a standard fs (file system) module, that contains different types of methods to manipulate the file system.

Using the readFileStr() method

The readFileStr() method is used to read the entire contents of a file in Deno.

Example:

app.js
import { readFileStr } from "https://deno.land/std/fs/mod.ts";

const text = await readFileStr("./songs.txt", { encoding: "utf8" });

console.log(text);

The first argument in the readFilestr() method is file path and second argument is the type of encoding to read the file.

To run it, we need to allow deno to read the ./songs.txt file by using --allow-read flag.

deno run --unstable  --allow-read=songs.txt app.js

Output:

my first song.

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 readFileStrSync() method to read the file synchronously.

app.js
import { readFileStrSync } from "https://deno.land/std/fs/mod.ts";

const text = readFileStrSync("./songs.txt", { encoding: "utf8" });

console.log(text);

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 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)
221,520 students enrolled
44 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)
114,575 students enrolled
21 hours of video content
View Course