How to use the readdir function from graceful-fs

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

graceful-fs.readdir is a method in Node.js that reads the contents of a directory.

151
152
153
154
155
156
157
158
159
160
    })
  })
}

function copyDir (dir) {
  fs.readdir(dir, function (err, items) {
    if (err) return onError(err)
    items.forEach(function (item) {
      startCopy(path.join(dir, item))
    })
fork icon1
star icon0
watch icon0

449
450
451
452
453
454
455
456
457
458
459
}


// similar to chmodr except it add permissions rather than overwriting them
// adapted from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function addModeRecursive (cachedRemote, mode, cb) {
  fs.readdir(cachedRemote, function (er, children) {
    // Any error other than ENOTDIR means it's not readable, or doesn't exist.
    // Give up.
    if (er && er.code !== 'ENOTDIR') return cb(er)
    if (er || !children.length) return addMode(cachedRemote, mode, cb)
fork icon0
star icon1
watch icon1

How does graceful-fs.readdir work?

graceful-fs.readdir is a method in Node.js that asynchronously reads the contents of a directory and returns an array of file names or directory names. It is a wrapper around the fs.readdir method that handles errors more gracefully. It accepts a path to the directory as its first argument and an optional options object as its second argument.

200
201
202
203
204
205
206
207
208
209

if (!args) args = []

var f = path.join(npm.cache, normalize(args))
if (f === npm.cache) {
  fs.readdir(npm.cache, function (er, files) {
    if (er) return cb()
    asyncMap(
      files.filter(function (f) {
        return npm.config.get('force') || f !== '-'
fork icon0
star icon1
watch icon1

+ 14 other calls in file

204
205
206
207
208
209
210
211
212
213
    readdirRec.apply(null, args);
  })
  return;
}

fs.readdir(currentDir, function (err, entries) {
  if (err) {
    handleError(err);
    callCurrentDirProcessed();
    return;
fork icon0
star icon0
watch icon1

+ 10 other calls in file

Ai Example

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

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

  console.log(files);
});

In this example, graceful-fs.readdir is used to read the contents of the directory located at /path/to/directory. The function takes a callback as its second argument, which is called with two arguments: an error (if one occurs), and an array of filenames in the directory. If there are no errors, the array of filenames is logged to the console.