当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js fs.Dir.closeSync()用法及代码示例


fs.Dir.closeSync()方法是文件系统模块中fs.Dir类的内置应用程序编程接口,用于同步关闭目录的基础资源句柄。

用法:

const dir.closeSync()

参数:此方法不接受任何参数。

返回值:此方法返回一个未定义的对象

下面的程序演示了fs.Dir.closeSync()方法的使用。



范例1:
文件名:index.js

// Node.js program to demonstrate the  
// dir.closeSync() method 
const fs = require('fs'); 
   
// Initiating asyn function 
async function stop(path) { 
   
  // Creating and initiating directory's  
  // underlying resource handle 
  const dir = await fs.promises.opendir(path); 
  
  console.log("All the dirent beofre operation:- "); 
  for (var i = 0; i <= 6; i++) { 
     console.log(((dir.readSync())).name); 
  } 
     
  // Synchronously closeSyncing the directory's 
  // underlying resource handle 
  const promise = dir.closeSync(); 
  
  // Display the result 
  console.log("dir is closed successfully"); 
} 
   
// Catching error 
stop('./').catch(console.error);

使用以下命令运行index.js文件:

node index.js

输出:

All the dirent beofre operation:-
abcd.cer
books.txt
cert.cer
certfile.cer
certificate1.cer
example.txt
features
dir is closed successfully

范例2:
文件名:index.js

// Node.js program to demonstrate the  
// dir.closeSync() method 
const fs = require('fs'); 
const fsPromises = fs.promises; 
  
// Name of the directory to be created 
let directo = './temp'; 
  
// Checking if the directory is present or not 
if (!fs.existsSync(directo)){ 
  fs.mkdirSync(directo); 
} 
     
// Initiating asynchronous function 
async function funct(path) { 
       
  // Initializng dir 
  let dir = null; 
  let pathval = null; 
     
  try { 
      
   // Creating and initiating directory's 
   // underlying resource handle 
   dir = await fs.promises.opendir( 
      new URL('file:///F:/java/temp')); 
  
   console.log("All the dirent before operation:- "
                 + ((dir.readSync()))); 
     
   // Getting the path of the directory 
   // by using path() method 
   pathval = dir.path; 
     
  } finally { 
     
    if (dir) { 
   
      // Close the file if it is opened. 
      console.log("Path:- " + pathval); 
  
      console.log("All the dirent beofre operation:- "
                          + ((dir.readSync()))); 
  
      console.log("dir is closed successfully"); 
   
      await dir.closeSync();    
    } 
  } 
} 
     
funct('./').catch(console.error);

使用以下命令运行index.js文件:

node index.js

输出:

All the dirent before operation:- [object Object]
Path:- F:
All the dirent before operation:- [object Object]
dir is closed successfully

参考: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dir_closesync




相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Node.js fs.Dir.closeSync() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。