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.
For anyone ending up here off a search looking for a flags reference, here it is:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With