Node.js: fs.open()

    Today, I would like to take a look at one of the widely used functions of Node.js' fs library - open(), and its synchronous version - openSync().

    The function's purpose is to open a file, specified by a path (the first mandatory parameter of the function). The code of the function is following (source):
function open(path, flags, mode, callback) {
  path = toPathIfFileURL(path);
  validatePath(path);
  if (arguments.length < 3) {
    callback = flags;
    flags = 'r';
    mode = 0o666;
  } else if (typeof mode === 'function') {
    callback = mode;
    mode = 0o666;
  }
  const flagsNumber = stringToFlags(flags);
  if (arguments.length >= 4) {
    mode = validateMode(mode, 'mode', 0o666);
  }
  callback = makeCallback(callback);

  const req = new FSReqCallback();
  req.oncomplete = callback;

  binding.open(pathModule.toNamespacedPath(path),
               flagsNumber,
               mode,
               req);
}


    Parameters "flags" and "mode" are optional. Parameter "callback" is mandatory to have. The default values for "flags" and "mode" are 'r' (open file for reading, an exception gets raised if file doesn't exist), "0o666" (readable/writable) respectively.


    Now, let's take a look at the synchronous version of the function (source):
function openSync(path, flags, mode) {
  path = toPathIfFileURL(path);
  validatePath(path);
  const flagsNumber = stringToFlags(flags || 'r');
  mode = validateMode(mode, 'mode', 0o666);

  const ctx = { path };
  const result = binding.open(pathModule.toNamespacedPath(path),
                              flagsNumber, mode,
                              undefined, ctx);
  handleErrorFromBinding(ctx);
  return result;
}

    Here, only "path" would be the required parameter, and "flags" and "mode" are optional and still have the same defaults. The function will be executed in synchronous manner, blocking the thread from further execution (until the function is finished).

    Examples of usage:
1. To open a file to read. An exception gets thrown if the file does not exist.
const fs = require('fs');
fs.open('file1.txt', 'r', (err) => {console.log(err);});


2. To open a file for reading and appending. The file is to be created if doesn't exist:
const fs = require('fs');
fs.open('file1.txt', 'a+', (err) => {console.log(err);});


3. To open a file synchronously in 'read' mode:
const fs = require('fs');
fs.openSync('file1.txt');

More detailed information regarding possible flags to use, can be found here.

Comments

Popular posts from this blog

Two Different Frames of Same VidioCapture

Good friend penguinV