What is the use of fd (file descriptor) in Node.js?
In your example, fd
is the second parameter of the callback
passed to fs.open
:
- What is important is that is the second parameter.
- Its name is not important.
That second parameter represents a file descriptor, useful to access that opened file inside the callback.
For example 1:
var fs = require("fs");
var fileName = "foo.txt";
fs.exists(fileName, function(exists) {
if (exists) {
// get information about the file
fs.stat(fileName, function(error, stats) {
// open the file (getting a file descriptor to it)
fs.open(fileName, "r", function(error, fd) {
var buffer = new Buffer(stats.size);
// read its contents into buffer
fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
var data = buffer.toString("utf8", 0, buffer.length);
console.log(data);
fs.close(fd);
});
});
});
}
});
there, you have fd
(the second parameter of fs.open
) passed to fs.read
as its first parameter, and so you can read that file.
1: Example taken from: http://www.sitepoint.com/accessing-the-file-system-in-node-js/
One crucial information of note is that fd
can used for both reading and writing at the same time. That is, essentially the use case of calling fs.open()
. It is useful if you want to perform several actions on the opened file.
Here is an example.
fs.open('<directory>', 'r+', (err, fd) => {
// r+ is the flag that tells fd to open it in read + write mode.
// list of all system flags: 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);
});
File descriptors are a concept used in many programming languages, they represent a reference to an opened file.
The file descriptor will be used to reference the correct file stream by all file system related functions.
In fact stdout, stdin and stderr get assigned a file descriptor too, they are occupying fd 0
through 2
, the next free file descriptor value is 3. Thats why the value returned in your example is 3
.
See Wikipedia for more background information.