fs module - fs.open()

open(): 

To create a file, to write to a file, or to read a file the fs.open() method is used.


Syntax:

    
    fs.open(filename, options, callback);


Example:


    
    var fs = require("fs");
    fs.open("mynewfile2.txt", "w", function (err, file) {
      if (err) throw err;
      console.log("Saved!");
    });



FLAG

DESCRIPTION

r

To open a file to read and throw an exception if the file doesn’t exist.

r+

Open file to read and write. Throw an exception if the file doesn’t exist.

rs+

Open file in synchronous mode to read and write.

w

Open file for writing. File is created if it doesn’t exist.

wx

It is the same as ‘w’ but fails if the path exists.

w+

Open file to read and write. File is created if it doesn’t exist.

wx+

It is the same as ‘w+’ but fails if the path exists.

a

Open file to append. File is created if it doesn’t exist.

ax

It is the same as ‘a’ but fails if the path exists.

a+

Open file for reading and appending. File is created if it doesn’t exist.

ax+

It is the same as ‘a+’ but fails if the path exists.


fs.openSync():


    
    fs.openSync(path, options);
    // Including fs module
    var fs = require("fs");

    // Defining filename
    var filename = "./myfile";

    // Calling openSync method
    // with its parameters

    var res = fs.openSync(filename, "r");
    // Prints output
    console.log(res);


Post a Comment

Previous Post Next Post