📜  Node.js fs.Dir.readSync() 方法

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

Node.js fs.Dir.readSync() 方法

fs.Dir.readSync()方法是文件系统模块中fs.Dir类的内置应用程序编程接口,用于读取目录的每个下一个目录。
句法:

const dir.readSync()

参数:此方法不接受任何参数。
返回值:该方法返回目录的dirent。
下面的程序说明了 Node.js 中fs.Dir.readSync()方法的使用:
示例 1:
文件名:index.js

javascript
// Node.js program to demonstrate the
// dir.readSync() method
const fs = require('fs');
 
// Initiating async function
async function stop(path) {
 
  // Creating and initiating directory's
  // underlying resource handle
  const dir = await fs.promises.opendir(path);
   
  // Synchronously reading the directory's
  // underlying resource handle
  const dirent = dir.readSync();
 
  // Display the result
  console.log(dirent.name);
}
 
// Catching error
stop('./').catch(console.error);


javascript
// Node.js program to demonstrate the
// dir.readSync() method
const fs = require('fs');
   
// Initiating async function
async function stop(path) {
  
  let dir = null;
  
  try {
 
  // Creating and initiating directory's
  // underlying resource handle
  dir = await fs.promises.opendir(
      new URL('file:///F:/java/'));
 
  // Synchronously reading the directory's
  // underlying resource handle
  // using readSync() method
  for(var i = 0 ; i <= 3 ; i ++ ) {
    var dirent = dir.readSync();
 
    // Display the result
    console.log(dirent.name);
  }
 
  } finally {
  
    if (dir) {
 
      // Display the result
      console.log("dir is closed successfully");
 
      // Synchronously closeSyncing the
      // directory's underlying resource
      // handle
      const promise = dir.closeSync()
    }
  }
}
   
// Catching error
stop('./').catch(console.error);


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

node index.js

输出:

abcd.cer

示例 2:
文件名:index.js

javascript

// Node.js program to demonstrate the
// dir.readSync() method
const fs = require('fs');
   
// Initiating async function
async function stop(path) {
  
  let dir = null;
  
  try {
 
  // Creating and initiating directory's
  // underlying resource handle
  dir = await fs.promises.opendir(
      new URL('file:///F:/java/'));
 
  // Synchronously reading the directory's
  // underlying resource handle
  // using readSync() method
  for(var i = 0 ; i <= 3 ; i ++ ) {
    var dirent = dir.readSync();
 
    // Display the result
    console.log(dirent.name);
  }
 
  } finally {
  
    if (dir) {
 
      // Display the result
      console.log("dir is closed successfully");
 
      // Synchronously closeSyncing the
      // directory's underlying resource
      // handle
      const promise = dir.closeSync()
    }
  }
}
   
// Catching error
stop('./').catch(console.error);

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

node index.js

输出:

abcd.cer
cert.cer
certfile.cer
certificate1.cer
dir is closed successfully

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