Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 917
Venkat Ch Avatar asked Feb 22 '18 13:02

Venkat Ch


2 Answers

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);
});
like image 106
Shwetabh Shekhar Avatar answered Sep 23 '22 10:09

Shwetabh Shekhar


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:

Node.js FS

like image 26
Giannis Mp Avatar answered Sep 20 '22 10:09

Giannis Mp