在 fs.writeFile([option]) 中,"options parameter" 通常如何工作?

In fs.writeFile([option]), how an "options parameter" generally work?

我正在阅读这篇关于 Node.js 文件系统 fs.writeFile(filename, data, [options], callback) 的文档。 所以我注意到我经常看到[选项],但从来没有用过它。有人可以给我举个例子吗?我所有的案例都没有使用这个选项。

这些是选项。

  1. 编码(字符串或NULL),默认值为'utf8'
  2. 模式(数字),默认值为 438(即八进制中的 0666)
  3. flag(字符串),默认值为'w'

我猜您对 options 参数在 javascript 中的一般工作方式感兴趣。

相反,参数是stated in the docs:

  • options Object
    • encoding String | Null default = 'utf8'
    • mode Number default = 438 (aka 0666 in Octal)
    • flag String default = 'w'

一般来说,options参数是一个对象,其属性就是你要修改的选项。因此,如果您想修改 fs.writeFile 上的两个选项,您可以将每个选项作为 属性 添加到 options:

fs.writeFile(
    "foo.txt",
    "bar",
    {
        encoding: "base64",
        flag: "a"
    },
    function(){ console.log("done!") }
)

如果您对这三个参数的用途感到困惑,the docs for fs.open 拥有您需要的一切。它包括 flag 的所有可能性以及 mode 的描述。 callbackwriteFile 操作完成后被调用。

fs.writeFile(filename,data,{flag: "wx"},function(err){
    if(err) throw err
    console.log('Date written to file, ',filename)
})

正如您在上面的代码片段中看到的,第三个参数是options/flag。有optional和用来表示文件打开时的行为。

我已将 "wx" 作为选项传递,这表明文件将打开以进行写入,如果文件不存在则将被创建。但如果已经存在,它将失败。

默认情况下 "w" 作为选项传递。

要进一步阅读不同的选项,here

对于任何结束这里寻找标志参考的搜索,这里是:

Flag Description
r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like 'w' but fails if the path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if the the path exists.