In Deno, writing files can be achieved through various methods, including the use of high-level APIs from the standard library or low-level system calls. Below, I'll introduce two common methods for writing files:
Method 1: Using Deno.writeTextFile
This is the simplest method for writing files, suitable for scenarios where you need to quickly write text data to a file. This function directly takes the file path and the string data to write, and Deno handles all operations such as opening the file, writing the content, and closing the file.
typescriptasync function writeFile() { const text = 'Hello, Deno!'; try { await Deno.writeTextFile("./example.txt", text); console.log("File written successfully"); } catch (error) { console.error("File write failed:", error); } } writeFile();
Method 2: Using Deno.open and Deno.write
If you need finer control, such as performing additional operations before writing data (e.g., reading file status or appending data instead of overwriting), you can use the Deno.open method to open the file and then use Deno.write or Deno.writeFile to write the data.
typescriptasync function writeToFile() { const encoder = new TextEncoder(); const data = encoder.encode("Hello, Deno with more control!"); try { const file = await Deno.open("./more_control_example.txt", { write: true, create: true }); await Deno.write(file.rid, data); file.close(); console.log("File written successfully"); } catch (error) { console.error("File write failed:", error); } } writeToFile();
Notes
When writing files in Deno, ensure the program has the necessary permissions. For example, when running the above script from the command line, you may need to add the --allow-write flag to authorize file writing operations:
bashdeno run --allow-write script.ts
These methods provide different levels of flexibility and control, allowing you to choose based on specific needs.