📜  Node.js fs.close() 方法

📅  最后修改于: 2022-05-13 01:56:31.491000             🧑  作者: Mango

Node.js fs.close() 方法

fs.close() 方法用于异步关闭给定的文件描述符,从而清除与其关联的文件。这将允许文件描述符被重用于其他文件。在文件描述符上调用 fs.close() 时正在对其执行一些其他操作可能会导致未定义的行为。

句法:

fs.close( fd, callback )

参数:此方法接受上面提到的两个参数,如下所述:

  • fd:它是一个整数,表示要关闭的文件的文件描述符。
  • 回调:它是一个在方法执行时将被调用的函数。
    • err:如果方法失败会抛出一个错误。

下面的示例说明了 Node.js 中的fs.close() 方法

示例 1:此示例显示文件描述符的关闭。

// Node.js program to demonstrate the
// fs.close() method
  
// Import the filesystem module
const fs = require('fs');
  
// Get the file descriptor of the given path
file_descriptor = fs.openSync("example.txt");
console.log("The file descriptor is:", file_descriptor);
  
// Close the file descriptor
fs.close(file_descriptor, (err) => {
  if (err)
    console.error('Failed to close file', err);
  else {
    console.log("\n> File Closed successfully");
  }
});

输出:

The file descriptor is: 3

> File Closed successfully

示例 2:此示例显示文件描述符的关闭并尝试再次访问该关闭的文件描述符。

// Node.js program to demonstrate the
// fs.close() method
  
// Import the filesystem module
const fs = require('fs');
  
// Get the file descriptor of the given path
file_descriptor = fs.openSync("example.txt");
console.log("The file descriptor is:", file_descriptor);
  
console.log("\n> Finding the stats of the file");
try {
  
  // Attempting to find stats of file before closing
  statsObj = fs.fstatSync(file_descriptor);
  console.log("Stats of the file generated");
  
  // Closing the file descriptor
  console.log("\n> Closing the file descriptor");
  fs.close(file_descriptor, (err) => {
    if (err)
      console.error("Failed to close file", err);
    else {
      console.log("File Closed successfully");
  
      try {
        // Attempting to find stats of file after closing
        console.log("\n> Finding the stats of the file again");
        statsObj = fs.fstatSync(file_descriptor);
        console.log("Stats of the file generated");
      }
      catch (err) {
        console.error("Cannot find stats of file", err);
      }
    }
  });
  
} catch (err) {
  console.error("Cannot find stats of file", err);
}

输出:

The file descriptor is: 3

> Finding the stats of the file
Stats of the file generated

> Closing the file descriptor
File Closed successfully

> Finding the stats of the file again
Cannot find stats of file Error: EBADF: bad file descriptor, fstat
    at Object.fstatSync (fs.js:897:3)
    at G:\tutorials\nodejs-fs-close\index.js:42:23
    at FSReqCallback.oncomplete (fs.js:146:23) {
  fd: 3,
  errno: -4083,
  syscall: 'fstat',
  code: 'EBADF'
}

参考: https://nodejs.org/api/fs.html#fs_fs_close_fd_callback