Skip to content
DeveloperMemos

Reading and Writing Files in Deno using node:fs

Deno, JavaScript, File IO1 min read

When it comes to working with files in JavaScript, Node.js has always been the go-to solution. However, Deno, a secure runtime for JavaScript and TypeScript, offers file system utilities that make it easy to work with files as well. In this article, we'll explore how to read and write files in Deno using 'node:fs'.

Reading Files

To read a file in Deno, you can use the readFileSync function from the node:fs module. This function takes the path of the file as an argument and returns the contents of the file as a Uint8Array. Here's an example:

1import { readFileSync } from "node:fs";
2
3const data = readFileSync("file.txt");
4console.log(data.toString());

In this example, we import the readFileSync function from the node:fs module and pass the path of the file we want to read as an argument. The function returns the contents of the file as a Uint8Array, which we convert to a string using the toString() method before logging it to the console.

Writing Files

To write to a file in Deno, you can use the writeFileSync. This function takes two arguments: the path of the file to write to and the data to write. Here's an example:

1import { writeFileSync } from "node:fs";
2
3const data = "Hello, world!";
4writeFileSync("file.txt", data);

Conclusion

Working with files in Deno is easy thanks to node compatability. With just a few lines of code, you can read from and write to files in your Deno applications. While Deno is still relatively new compared to Node.js, it's gaining traction among developers who value security and simplicity. If you're interested in trying out Deno, I highly recommend it!