Course contentsShow
← JavaScript
Lesson 1526 of 2,72333. JavaScript in Node.jsFree lesson

File Descriptors and fs.open()/fs.close()

Low-level file operations using file descriptors for fine-grained control.

File Descriptors and fs.open()/fs.close()

You'll learn how to work with low-level file operations using file descriptors for precise control over file handling.

What is a File Descriptor?

A file descriptor is a numeric identifier that the operating system assigns to an open file. Think of it like a ticket number at a deli counter—when you open a file, the OS hands you a number, and you use that number for all subsequent operations (reading, writing, closing) on that file.

While higher-level methods like fs.readFile() handle opening and closing files automatically behind the scenes, fs.open() and fs.close() give you manual control over this process.

Opening Files with fs.open()

Use fs.open() when you need fine-grained control:

const fs = require('fs');

fs.open('myfile.txt', 'r', (err, fd) => {
  if (err) throw err;
  console.log('File descriptor:', fd); // Example output: 3
  
  // Now you can use 'fd' with other low-level operations
  
  // Always close when done!
  fs.close(fd, (err) => {
    if (err) throw err;
    console.log('File closed');
  });
});

The second argument is a flag: 'r' for reading, 'w' for writing, 'a' for appending.

Why Use File Descriptors?

File descriptors are essential when you need to:

  • Perform multiple operations on the same open file
  • Control exactly when files open and close
  • Use specialized methods like fs.read() or fs.write() that require a descriptor
  • Manage system resources carefully in high-performance scenarios

Key Takeaway: File descriptors provide low-level access to files through numeric identifiers obtained with fs.open(), giving you precise control over file operations—just remember to always fs.close() when finished to avoid resource leaks.