Read and write files
- Deno’s runtime API provides the Deno.readTextFile and asynchronous functions for reading and writing entire text files.
- Use and
--allow-write
permissions to gain access to the file system.
As highlighted in the Fetch Data example Deno restricts access to Input / Output by default for security reasons. Therefore when interacting with the filesystem the --allow-read
and --allow-write
flags must be used with the deno run
command.
The Deno runtime API makes it possible to read text files via the method, it just requires a path string or URL object. The method returns a promise which provides access to the file’s text data.
Command: deno run --allow-read read.ts
`
The Deno runtime API allows developers to write text to files via the Deno.writeTextFile()
method. It just requires a file path and text string. The method returns a promise which resolves when the file was successfully written.
To run the command the --allow-write
flag must be supplied to the deno run
command.
Command:
`
By combining Deno.writeTextFile
and JSON.stringify
you can easially write serialized JSON objects to a file. This example uses synchronous Deno.writeTextFileSync
, but this can also be done asynchronously using await Deno.writeTextFile
.
To execute the code the command needs the write flag.
Command: deno run --allow-write write.ts
`