I was confused with this, that I found on the document in the nodejs.
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
?
I was confused with this, that I found on the document in the nodejs.
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
?
1 Answer
Reset to default 4The 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);
};