Instructions for the fs.open method in node.js

  • 2020-05-07 19:13:22
  • OfStack

method description:

Open the file asynchronously.

In POSIX systems, path is considered to exist by default (even if the file under the path does not exist)

The flag identity may or may not run under the network file system.

syntax:


fs.open(path, flags, [mode], [callback(err,fd)])

Since this method belongs to the fs module, the fs module (var fs= require(" fs ")) should be introduced before use.

receive parameters:

path         file path

flags         can be the following value


'r' -   Open the file in read mode.
'r+' - Open the file in read/write mode.
'rs' - Open and read the file in synchronous mode. Instructs the operating system to ignore the local file system cache.
'rs+' - Open and read synchronously and Write to a file.
Note: this is not letting fs.open A blocking operation that changes to synchronous mode. Use it if you want to synchronize the mode fs.openSync() .
 
'w' - Open the file in read mode and create it if it does not exist
'wx' - and ' w ' model 1 Returns failure if the file exists
'w+' - Open the file in read/write mode and create it if it does not exist
'wx+' - and ' w+ ' model 1 Returns failure if the file exists
 
'a' - Open the file in append mode and create it if it does not exist
'ax' - and ' a ' model 1 Returns failure if the file exists
'a+' - Open the file in read append mode and create it if it does not exist
'ax+' - and ' a+ ' model 1 Returns failure if the file exists
mode    Used to assign permissions to a file when it is created, by default 0666

The callback   callback function passes one file descriptor, fd, and one exception, err

example:


var fs = require('fs');
fs.open('/path/demo1.txt', 'a', function (err, fd) {
  if (err) {
    throw err;
  }
  fs.futimes(fd, 1388648322, 1388648322, function (err) {
    if (err) {
      throw err;
    }
    console.log('futimes complete');
    fs.close(fd, function () {
      console.log('Done');
    });
  });
});

source code:


fs.open = function(path, flags, mode, callback) {
  callback = makeCallback(arguments[arguments.length - 1]);
  mode = modeNum(mode, 438 /*=0666*/);
  if (!nullCheck(path, callback)) return;
  binding.open(pathModule._makeLong(path),
               stringToFlags(flags),
               mode,
               callback);
};


Related articles: