文件描述符


在 POSIX 系统上,对于每个进程,内核维护一个当前打开的文件和资源表。 每个打开的文件都分配了一个简单的数字标识符,称为文件描述符。 在系统级,所有文件系统操作都使用这些文件描述符来识别和跟踪每个特定文件。 Windows 系统使用不同但概念上相似的机制来跟踪资源。

分配后,文件描述符可用于从文件读取数据、向文件写入数据或请求有关文件的信息。

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.fstat(fd, (err, stat) => {
    if (err) throw err;
    // 使用统计

    // 
    fs.close(fd, (err) => {
      if (err) throw err;
    });
  });
});

否则将导致内存泄漏,最终导致应用程序崩溃。

On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a file descriptor. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the specific differences between operating systems and assigns all open files a numeric file descriptor.

The fs.open() method is used to allocate a new file descriptor. Once allocated, the file descriptor may be used to read data from, write data to, or request information about the file.

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.fstat(fd, (err, stat) => {
    if (err) throw err;
    // use stat

    // always close the file descriptor!
    fs.close(fd, (err) => {
      if (err) throw err;
    });
  });
});

Most operating systems limit the number of file descriptors that may be open at any given time so it is critical to close the descriptor when operations are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash.