0

As per deno documentation for writeFile if I want to write in a file and overwrite if the file already exists I need this command -

await Deno.writeFile("hello1.txt", data);  // overwrite "hello1.txt" or create it

What I need is to create an empty file and if a file with the same name already exists overwrite it with an empty file, so I tried to run the function without data and I am getting this error.

await Deno.writeFile("hello1.txt");
 An argument for 'data' was not provided.
        data: Uint8Array,

How can I create an empty file in Deno and overwrite any file exists with the same name?

Puneet Singh
  • 3,477
  • 1
  • 26
  • 39

3 Answers3

3

Pass an empty Uint8Array to Deno.writeFile

await Deno.writeFile("./hello1.txt", new Uint8Array());

You can also use Deno.open with truncate: true

await Deno.open("./hello1.txt", { create: true, write: true, truncate: true });

or Deno.create:

await Deno.create("./hello1.txt")

Alternatively, if you know the file already exists you can use Deno.truncate

await Deno.truncate("./hello1.txt");
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
2

You can use Deno.create:

Creates a file if none exists or truncates an existing file and resolves to an instance of Deno.File.

await Deno.create("hello1.txt")
Process deeper file paths with possibly not existent directories safely:
import { ensureFile } from "https://deno.land/std/fs/ensure_file.ts";
const file = "./deep/hello1.txt"; // `deep` doesn't need to exist
await ensureFile(file); // ensures file and containing directories
await Deno.truncate(file);
Community
  • 1
  • 1
ford04
  • 66,267
  • 20
  • 199
  • 171
1

You can use writeTextFile and pass an empty string. Rest as suggested above, use ensureFile and truncate for other needs.

(async function() {
  await Deno.writeTextFile("./helloworld.txt", "")
})()
xdeepakv
  • 7,835
  • 2
  • 22
  • 32