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

iamwave007 picture iamwave007 · Jan 13, 2015 · Viewed 23.3k times · Source

I was reading this document about Node.js file system, fs.writeFile(filename, data, [options], callback). So I noticed that i have seen the [options] pretty often, but never used it for anything. Can someone give me an example? All the cases i had didn't use this option.

Answer

uber5001 picture uber5001 · Jan 13, 2015

I'm guessing your interested in how an options parameter generally works in javascript.

As opposed to what the parameters are, which are stated in the docs:

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

Generally, the options parameter is an object, with properties that are the options you want to modify. So if you wanted to modify two of the options on fs.writeFile, you'd add each one as a property to options:

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

And if you're confused as to what these three params are used for, the docs for fs.open have everything you need. It includes all the possibilities for flag, and a description for mode. The callback is called once the writeFile operation is complete.