what is the use of fs.open() in nodejs, what is difference between fs.readfile and fs.open()

Venkat Ch picture Venkat Ch · Feb 22, 2018 · Viewed 7.3k times · Source

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?

Answer

Shwetabh Shekhar picture Shwetabh Shekhar · May 11, 2018

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