In fs.writeFile ([option]), how does the parameter parameter usually work?

I have read this document on file system Node.js, fs.writeFile(filename, data, [options], callback). Therefore, I noticed that I saw [options] quite often, but I never used it for anything. Can someone give me an example? All the cases that I used did not use this option.

+4
source share
3 answers

I assume you are interested in how a parameter optionsusually works in javascript.

Unlike the parameters specified in the documents :

  • parameters .
    • String Encoding | Null default = 'utf8'
    • = 438 (aka 0666 Octal)
    • default = 'w'

, options , , . , fs.writeFile, options:

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

, , fs.open , . flag mode. callback writeFile.

+9

.

  • ( NULL), "utf8"
  • mode (number), - 438 ( 0666 Octal)
  • (), - 'w'
+1
fs.writeFile(filename,data,{flag: "wx"},function(err){
    if(err) throw err
    console.log('Date written to file, ',filename)
})

As you can see in the above code snippet, the third parameter is the parameter / flag. There are optional and used to indicate the behavior of the file to be opened.

I passed "wx" as an option, which indicates that the file will be open for writing and will be created if it does not exist. But he will fail if he already exists.

By default, "w" is passed as an option.

For further reading of various options here

+1
source

All Articles