fs.closeSync()方法用於同步關閉給定的文件描述符,從而清除與之關聯的文件。它允許文件描述符重用於其他文件。在文件描述符上執行其他操作時,在文件描述符上調用fs.closeSync()可能會導致未定義的行為。
用法:
fs.closeSync( fd )
參數:此方法接受上述和以下描述的單個參數:
- fd:這是一個整數,表示要關閉的文件的文件描述符。
以下示例說明了Node.js中的fs.closeSync()方法:
範例1:本示例顯示文件描述符的關閉。
// Node.js program to demonstrate the
// fs.closeSync() 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
try {
fs.closeSync(file_descriptor);
console.log("\n> File Closed successfully");
} catch (err) {
console.error('Failed to close file');
}
輸出:
The file descriptor is:3 > File Closed successfully
範例2:本示例顯示了文件描述符的關閉,並嘗試再次訪問關閉的文件描述符。
// Node.js program to demonstrate the
// fs.closeSync() 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);
// Attempting to get stats before closing
console.log("\n> Finding the stats of the file");
try {
statsObj = fs.fstatSync(file_descriptor);
console.log("Stats of the file generated");
} catch (err) {
console.error('Cannot find stats of file', err);
}
// Close the file descriptor
try {
fs.closeSync(file_descriptor);
console.log("\n> File Closed successfully");
} catch (err) {
console.error('Failed to close file', err);
}
// Attempting to find stats after closing
console.log("\n> Finding the stats of the file again");
try {
statsObj = fs.fstatSync(file_descriptor);
console.log("Stats of the file generated");
} 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 > 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 Object. (G:\tutorials\nodejs-fs-closeSync\index.js:46:17) at Module._compile (internal/modules/cjs/loader.js:956:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10) at Module.load (internal/modules/cjs/loader.js:812:32) at Function.Module._load (internal/modules/cjs/loader.js:724:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) at internal/main/run_main_module.js:17:11 { fd:3, errno:-4083, syscall:'fstat', code:'EBADF' }
參考: https://nodejs.org/api/fs.html#fs_fs_closesync_fd
相關用法
- Node.js GM flop()用法及代碼示例
- Node.js GM spread()用法及代碼示例
- Node.js GM gamma()用法及代碼示例
- Node.js GM minify()用法及代碼示例
- Node.js GM magnify()用法及代碼示例
- Node.js GM modulate()用法及代碼示例
- Node.js GM gaussian()用法及代碼示例
- Node.js GM shave()用法及代碼示例
- Node.js GM emboss()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.closeSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。