Reputation: 736
I want to know what is the use of fs.open()
in nodejs application.
What is the difference between the open
and readfile
methods in nodejs, and how do they work?
Upvotes: 13
Views: 16113
Reputation: 3054
You'd call fs.open()
if you want to perform several actions on that file. Methods like fs.readFile()
are simply shortcuts that also prevent forgetting to close the file. (Especially less obvious cases like try/catch.) But you wouldn't want to constantly reopen and reclose the same file if you're working on it.
If you look at the documentation (http://nodejs.org/api/fs.html), the first argument for fs.read()
says fd while the first argument for fs.readFile()
is filename. The fd stands for "file descriptor" which is the object returned by fs.open(). The filename is simply a string.
Here is an example of leveraging the fd
for reading and writing.
fs.open('<directory>', 'r+', (err, fd) => {
// r+ is the flag that tells fd to open it in read + write mode.
// list of all flags available: https://nodejs.org/api/fs.html#fs_file_system_flags
// read using fd:https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback
// write using fd: https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback
// close the flag: fs.close(fd);
});
Upvotes: 15
Reputation: 36
Yes as stated above, if you use the fs.readFile() it will open the file for you and read the contents. You would use fs.open() if you want to do several operations or the operation is conditional. There are several examples in w3schools. https://www.w3schools.com/nodejs/nodejs_filesystem.asp
Upvotes: 2
Reputation: 1309
With fs.open() you open the file and can then can do several things to it. Read it, write it, close it etc.. With fs.readFile without having to open or close the file you read it. Check for more information:
Upvotes: 4