Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between fs.open 'rs' flag and fs.openSync

I was confused with this, that I found on the document in the nodejs.org.

It says that the rs flag in fs.open() is use to Open file for reading in synchronous mode.

It just makes me think this is a asynchronous file open but it's doing a synchronous read? I was really confused with this point.

After that it noted that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync().

What is the difference between fs.open's rs and fs.openSync's r?

like image 890
Lellansin Avatar asked Jul 31 '26 03:07

Lellansin


1 Answers

The difference is that one function expects a callback. The callback is passed to a low-level binding, so the function will be asynchronous regardless of the flags that you pass to it, hence the reason for the documentation to state that the flag "doesn't turn fs.open() into a synchronous blocking call". Take this example:

var fs = require('fs');
var file = './file';

// fd will always be defined
var fd = fs.openSync(file, 'r');

// fd is undefined because the function returns a
// binding, and the actually fs is passed in a callback
var fd = fs.open(file, 'rs');

Event if we don't pass a callback to the asynchronous function, the method isn't structured to return the resultant file descriptor. This is what the sources of the two functions look like:

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);
};

fs.openSync = function(path, flags, mode) {
  mode = modeNum(mode, 438 /*=0666*/);
  nullCheck(path);
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
};
like image 65
hexacyanide Avatar answered Aug 01 '26 16:08

hexacyanide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!