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

时间:2015-01-13 11:17:05

标签: node.js fs

我正在阅读有关Node.js文件系统fs.writeFile(filename, data, [options], callback)的文档。 所以我注意到我经常看到[选项],但从未用过任何东西。有人能举个例子吗?我没有使用过这个选项。

4 个答案:

答案 0 :(得分:14)

我猜你对options参数在javascript中的运作方式感兴趣。

参数是什么相反,stated in the docs

  
      
  • 选项 对象      
        
    • 编码 字符串 | Null default ='utf8'
    •   
    • 模式 数字默认= 438(八月份名为0666)
    •   
    • 标志 字符串默认='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的说明。 callback操作完成后,将调用writeFile

答案 1 :(得分:2)

对于那些在搜索结束时寻找标记引用的人来说,这里是:

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.

答案 2 :(得分:1)

这些是选项。

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

答案 3 :(得分:1)

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

正如您在上面的代码片段中看到的,第三个参数是选项/标志。有可选的,用于指示要打开的文件的行为。

我已通过“wx”作为选项,表示文件将打开以进行写入,如果不存在则将创建。但如果已经存在,它将失败。

默认情况下,“w”作为选项传递。

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