【问题标题】:How to create an empty file in Deno?如何在 Deno 中创建一个空文件?
【发布时间】:2020-06-13 21:03:05
【问题描述】:

根据deno documentation for writeFile,如果我想写入文件并在文件已经存在时覆盖我需要这个命令 -

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

我需要创建一个空文件,如果已经存在同名文件,用一个空文件覆盖它,所以我尝试在没有数据的情况下运行该函数,但出现此错误。

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

如何在 Deno 中创建一个空文件并覆盖已存在的同名文件?

【问题讨论】:

    标签: deno


    【解决方案1】:

    将空的Uint8Array 传递给Deno.writeFile

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

    您还可以将Deno.opentruncate: true 一起使用

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

    Deno.create:

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

    或者,如果您知道该文件已经存在,您可以使用Deno.truncate

    await Deno.truncate("./hello1.txt");
    

    【讨论】:

    • 谢谢,第一个选项工作得很好,但 Deno.truncate 不会创建一个空文件,它会清空现有文件。如果文件不存在,则会出错
    • 以为你一直有这个文件,我来修改答案。
    【解决方案2】:

    你可以使用Deno.create:

    如果不存在文件,则创建文件或截断现有文件并解析为Deno.File 的实例。

    await Deno.create("hello1.txt")
    
    安全地处理可能不存在目录的更深的文件路径:
    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);
    

    【讨论】:

      【解决方案3】:

      您可以使用writeTextFile 并传递一个空的string。按照上面的建议休息,其他需要使用ensureFile and truncate

      (async function() {
        await Deno.writeTextFile("./helloworld.txt", "")
      })()
      

      【讨论】:

        猜你喜欢
        • 2011-02-05
        • 1970-01-01
        • 2012-05-25
        • 1970-01-01
        • 2010-10-22
        • 1970-01-01
        • 2017-12-02
        • 1970-01-01
        • 2019-04-28
        相关资源
        最近更新 更多