Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

fs

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.

like image 943
iamwave007 Avatar asked Jan 13 '15 11:01

iamwave007


2 Answers

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.

like image 72
Artif3x Avatar answered Oct 10 '22 06:10

Artif3x


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.

like image 41
uber5001 Avatar answered Oct 10 '22 08:10

uber5001