— Deno, File I/O, Reading Files, Writing Files — 1 min read
Deno is a secure runtime for JavaScript and TypeScript that provides built-in support for reading and writing files. Whether you need to read data from a file or save data to a file, Deno offers simple and powerful APIs for file input/output (I/O) operations. In this article, we will dive into the basics of reading and writing files with Deno, along with some practical examples.
To read a file using Deno, you can utilize the Deno.readTextFile()
function. This function takes the path to the file as a parameter and returns a promise that resolves to the content of the file as a string. Let's see an example:
1const filePath = "/path/to/file.txt";2const fileContent = await Deno.readTextFile(filePath);3console.log(fileContent);
In this example, we specify the path to the file we want to read (filePath
). The await
keyword helps us handle the asynchronous nature of file reading in Deno. Once the promise is resolved, we can access the content of the file through the fileContent
variable.
To write data to a file using Deno, we can use the Deno.writeTextFile()
function. This function takes the file path and the content to be written as parameters. It returns a promise that resolves when the file is successfully written. Here's an example:
1const filePath = "/path/to/new-file.txt";2const content = "Hello, Deno!";3
4await Deno.writeTextFile(filePath, content);5console.log("File written successfully!");
In this example, we specify the path where we want to create the new file (filePath
) and the content we want to write (content
). The await
keyword ensures that the file is fully written before moving on to the next line of code.
It's important to note that Deno has security restrictions in place to protect your system. By default, Deno grants read-only access to files, so if you attempt to write a file without the necessary permissions, it will throw an error. To grant write access explicitly, you can use the --allow-write
flag when running your Deno script:
1deno run --allow-write your-script.ts
Similarly, for reading files, you can use the --allow-read
flag:
1deno run --allow-read your-script.ts
Make sure to specify the appropriate flags depending on the file I/O operations your script requires.
In this article, we covered the basics of reading and writing files with Deno. We explored the Deno.readTextFile()
function for reading files and the Deno.writeTextFile()
function for writing files. Remember to handle file permissions properly to ensure your scripts have the necessary access rights for file I/O operations. Deno offers a secure and straightforward approach to file handling in JavaScript and TypeScript, making it a reliable choice for working with files in your projects.