How to use the readdir function from fs-extra

Find comprehensive JavaScript fs-extra.readdir code examples handpicked from public code repositorys.

The fs-extra.readdir method is used to read the contents of a directory in Node.js, similar to the built-in fs.readdir, but with additional functionality.

220
221
222
223
224
225
226
227
228
229

const installDirectory = getInstallLocation()
const kitDependency = getChosenKitDependency()

await fs.ensureDir(installDirectory)
if ((await fs.readdir(installDirectory)).length > 0) {
  console.error(`Directory ${installDirectory} is not empty, please specify an empty location.`)
  process.exitCode = 3
  return
}
fork icon234
star icon281
watch icon77

+ 14 other calls in file

724
725
726
727
728
729
730
731
732
733
async function cleanupMountDirectories() {
  try {
    const tmpDir = os.tmpdir();
    // Enumerate all directories in the OS tmp directory and remove
    // any old ones
    const dirs = await fs.readdir(tmpDir);
    const outDirs = dirs.filter((d) => d.indexOf(MOUNT_DIRECTORY_PREFIX) === 0);
    await Promise.all(
      outDirs.map(async (dir) => {
        const absolutePath = path.join(tmpDir, dir);
fork icon250
star icon246
watch icon14

+ 7 other calls in file

How does fs-extra.readdir work?

The fs-extra.readdir function is used to asynchronously read the contents of a directory and returns a promise that resolves to an array of the names of the files and subdirectories in the directory. It takes two arguments: The path of the directory to read. An optional options object that can be used to configure the behavior of the function, such as sorting the results. Internally, the function uses the fs.readdir function from the Node.js fs module with additional functionality for handling errors and ensuring that the promise is always resolved or rejected.

220
221
222
223
224
225
226
227
228
229
};

let dirs = [[module.path, ""]];
while (dirs.length) {
	let [dir, relativeDir] = dirs.pop();
	for (let entry of await fs.readdir(dir, { withFileTypes: true })) {
		let fsPath = path.join(dir, entry.name);
		let relativePath = path.posix.join(relativeDir, entry.name);

		if (entry.isFile()) {
fork icon58
star icon228
watch icon0

17
18
19
20
21
22
23
24
25
26
 *     directory contains no files.
 */
async function getNewestFile(directory, filter = (name) => true) {
	let newestTime = new Date(0);
	let newestFile = null;
	for (let entry of await fs.readdir(directory, { withFileTypes: true })) {
		if (entry.isFile()) {
			let stat = await fs.stat(path.join(directory, entry.name));
			if (filter(entry.name) && stat.mtime > newestTime) {
				newestTime = stat.mtime;
fork icon58
star icon228
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
const fs = require("fs-extra");

fs.readdir("/path/to/directory", (err, files) => {
  if (err) {
    console.error(err);
  } else {
    console.log(files);
  }
});

In this example, we use fs-extra to read the contents of the directory located at /path/to/directory. The readdir() method takes a callback function as its second argument, which is called with an error object if there was an error reading the directory, or an array of strings representing the names of the files in the directory.

193
194
195
196
197
198
199
200
201
202
await fs.copy(path.resolve(process.cwd(), `sidecar`), sidecarDst, {
  preserveTimestamps: true,
});

(async function getFiles(dir) {
  const dirents = await fs.readdir(dir, { withFileTypes: true });
  await Promise.all(
    dirents.map((dirent) => {
      const res = path.resolve(dir, dirent.name);
      return dirent.isDirectory()
fork icon15
star icon187
watch icon0

215
216
217
218
219
220
221
222
223
224
    console.log("Input path written to project file.");
} else if (entry.isDirectory) {
    sessionStorage.setItem("multiInput", "true");
    let file = item.getAsFile();
    let dir = file.path;
    fs.readdir(dir, function (err, files) {
        if (err) {
            return console.log('Unable to scan directory: ' + err);
        }
        videoInputText.textContent = files.length + " files selected";
fork icon15
star icon172
watch icon7

+ 8 other calls in file

780
781
782
783
784
785
786
787
788
789
)

// Change package.json to .bower.json in dependencies' folders
.then(() =>
    fs.existsSync(`${fixtureDirPath}/bower_components`)
        ? fs.readdir(`${fixtureDirPath}/bower_components`)
        : [],
)

// Don't try to look into files.
fork icon30
star icon115
watch icon0

+ 7 other calls in file

6
7
8
9
10
11
12
13
14
15
16
17


function buildSass(srcDir, destDir) {
  fs.mkdir(destDir, { recursive: true });


  // Compile all the .scss files in ./src/_sass
  fs.readdir(srcDir, (_err, files) => {
    files.forEach((file) => {
      if (path.extname(file) == '.scss') {
        const p = path.parse(path.join(destDir, file));
        p.base = undefined;
fork icon9
star icon32
watch icon2

+ 8 other calls in file

44
45
46
47
48
49
50
51
52
53
  __dirname,
  `deployed/${network.name == "hardhat" ? "localhost" : network.name}/${version}/contracts`,
);
let addresses = {};
try {
  const files = await fs.readdir(currentPath);
  await Promise.all(
    files.map(async item => {
      if (path.extname(item) == ".json") {
        const contract = await fs.readJson(`${currentPath}/${item}`);
fork icon6
star icon34
watch icon4

+ 2 other calls in file

111
112
113
114
115
116
117
118
119
120
if (dataset.isVirtual || dataset.isMetaOnly) return []
const dir = exports.dir(dataset)
if (!await fs.pathExists(dir)) {
  return []
}
const files = await fs.readdir(dir)
const results = []
if (dataset.originalFile) {
  if (!files.includes(dataset.originalFile.name)) {
    console.warn('Original data file not found', dir, dataset.originalFile.name)
fork icon6
star icon26
watch icon4

+ 5 other calls in file

76
77
78
79
80
81
82
83
84
const pathExists = await fs
  .stat(sysPath.join(root, dir))
  .then((stat) => stat.isDirectory())
  .catch(() => false);
const srcDirents = pathExists
  ? await fs.readdir(sysPath.join(root, dir), {
      withFileTypes: true,
    })
  : [];
fork icon5
star icon36
watch icon0

819
820
821
822
823
824
825
826
827
828
let pluginName = req.body.pluginname;
let mainDir = path.join(backendDir, "web", "assets", pluginName);
var results = {};
let walk = function(dir, done) {
    
    fs.readdir(dir, function(err, list) {
      if (err) return done(err);
      var pending = list.length;
      let foldername = dir.substring(mainDir.length+1);
        if(foldername == ""){foldername="root";}
fork icon3
star icon30
watch icon0

233
234
235
236
237
238
239
240
241
242
- fs.createWriteStream():创建可写文件流
- fs.link():创建指向文件的新硬链接
- fs.mkdir(): 新建一个文件夹
- fs.mkdtemp():创建一个临时目录
- fs.open():设置文件模式
- fs.readdir():读取目录的内容
- fs.readFile():读取文件的内容。有关:fs.read()
- fs.readlink():读取符号链接的值
- fs.realpath():将相对文件路径指针(.,..)解析为完整路径
- fs.rename():重命名文件或文件夹
fork icon0
star icon12
watch icon1

+ 13 other calls in file

1821
1822
1823
1824
1825
1826
1827
1828
1829
let PublicationZIP = new JSZip();
files = await fs.readdir('./PDF/Letter/libretexts/' + zipFilename);
for (let i = 0; i < files.length; i++) {
    individualZIP.file(files[i], await fs.readFile(`./PDF/Letter/libretexts/${zipFilename}/${files[i]}`));
}
files = await fs.readdir(`./PDF/Letter/Finished/${zipFilename}/Publication`);
for (let i = 0; i < files.length; i++) {
    PublicationZIP.file(files[i], await fs.readFile(`./PDF/Letter/Finished/${zipFilename}/Publication/${files[i]}`));
}
fork icon8
star icon11
watch icon6

+ 17 other calls in file

28
29
30
31
32
33
34
35
36
	});
	await bundle.write({
		file: path.join(TEMP_DIR, 'bundle.js'),
		format: 'es'
	});
	const fileNames = (await readdir(TEMP_DIR)).sort();
	await remove(TEMP_DIR);
	assert.deepStrictEqual(fileNames, ['chunk.js', 'input.js']);
});
fork icon7
star icon17
watch icon1

+ 17 other calls in file

969
970
971
972
973
974
975
976
977
978
beforeChildren: async ({ definition, target }) => {
  const deployWithDir = `${target}/deploy-with`
  if (!(await fs.pathExists(deployWithDir))) {
    return
  }
  const depoyWithFiles = await fs.readdir(deployWithDir)

  if (!definition.deployWith) {
    definition.deployWith = {}
  }
fork icon0
star icon7
watch icon5

+ 5 other calls in file

33
34
35
36
37
38
39
40
41
42
outputJsVarAsync = (fname, varName, obj) =>
                      fse.outputFile(getAbsPath(fname),"export var " +varName + " = " +JSON.stringify(obj))
outputFileAsync = (fname, data) => fse.outputFile(getAbsPath(fname),data)
readFileAsync = (fname, encoding) => fse.readFile(getAbsPath(fname),encoding)
readJsonAsync = fname => fse.readJSON(getAbsPath(fname))
readdirAsync = dirname => fse.readdir(getAbsPath(dirname))
statAsync = path => fse.stat(getAbsPath(path))
readJson = fname => fse.readJSON(getAbsPath(fname))
pathExistsAsync = fname => fse.pathExists(getAbsPath(fname))
copyAsync = (src, dest) => fse.copy(src,dest)
fork icon1
star icon3
watch icon3

97
98
99
100
101
102
103
104
105
106
  return getFileBody(root, path);
}
if (path.substr(-1) == "/") {
  path = path.substr(0, path.length - 1);
}
return fs.readdir(rootPath).then(function (fns) {
  var dirs = [];
  var files = [];
  fns.sort().filter(function (fn) {
    var fullPath = fspath.join(path, fn);
fork icon0
star icon2
watch icon0

1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
} else {
    const strategiesPath = path.join(
        process.cwd(),
        "modules/strategies"
    );
    return fs.readdir(
        strategiesPath,
        function (err, strategiesFiles) {
            if (err) {
                console.error(err);
fork icon0
star icon2
watch icon3

+ 9 other calls in file

168
169
170
171
172
173
174
175
176
177
	this.docFolderPath = path.resolve(__dirname, '../../docs');
	this.docFolderRelativePath = this.docFolderPath.replace(process.cwd(), '');
}

async setPackagesList () {
	this.packages = (await readdir(this.packagesFolderPath)).filter((x) => {
		return testOnPackages.length
			? !(/(\.d)?\.ts$/).test(x) && testOnPackages.includes(x)
			: !(/(\.d)?\.ts$/).test(x) && !PrivatePackagesFolder.includes(x);
	});
fork icon0
star icon2
watch icon3

+ 15 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)