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:
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.
import { readFileStrSync } from "https://deno.land/std/fs/mod.ts";
const text = readFileStrSync("./songs.txt", { encoding: "utf8" });
console.log(text);