How to use the readdir function from fs

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

19
20
21
22
23
24
25
26
27
28
* fs.createWriteStream(): 创建可写的文件流。
* fs.link(): 新建指向文件的硬链接。
* fs.mkdir(): 新建文件夹。
* fs.mkdtemp(): 创建临时目录。
* fs.open(): 设置文件模式。
* fs.readdir(): 读取目录的内容。
* fs.readFile(): 读取文件的内容。相关方法:fs.read()。
* fs.readlink(): 读取符号链接的值。
* fs.realpath(): 将相对的文件路径指针(.、..)解析为完整的路径。
* fs.rename(): 重命名文件或文件夹。
fork icon192
star icon570
watch icon16

+ 5 other calls in file

1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252


app.post("/getallchatsofchatacter", jsonParser, function(request, response){
    if(!request.body) return response.sendStatus(400);


    var char_dir = (request.body.avatar_url).replace(`.${characterFormat}`,'');
    fs.readdir(chatsPath+char_dir, (err, files) => {
        if (err) {
          console.error(err);
          response.send({error: true});
          return;
fork icon60
star icon276
watch icon17

+ 2 other calls in file

513
514
515
516
517
518
519
520
521
522
  assert.strictEqual(err.code, 'ENOENT');
  assert.strictEqual(err.syscall, 'scandir');
  return true;
};

fs.readdir(nonexistentFile, common.mustCall(validateError));

assert.throws(
  () => fs.readdirSync(nonexistentFile),
  validateError
fork icon42
star icon19
watch icon0

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
const { readdir } = require('fs').promises


async function getFiles(currentDir, baseDir) {
  const dir = path.resolve(baseDir, currentDir)
  logger(`reading ${dir} (${currentDir} in ${baseDir})`)
  const dirents = await readdir(dir, { withFileTypes: true })
  const files = await Promise.all(
    dirents.map(dirent => {
      const res = `${currentDir}/${dirent.name}`
      return dirent.isDirectory() ? getFiles(res, baseDir) : res
fork icon11
star icon50
watch icon1

9
10
11
12
13
14
15
16
17
18
 * Renames file common/helpers/ptrit.h to common/helpers/ptritx.h
 * -----------------------------------------------------------------------------
 */

/**
 * Promisified version of fs.readdir
 * 
 * @method readdirAsync
 * 
 * @param {string} path
fork icon7
star icon10
watch icon3

+ 3 other calls in file

36
37
38
39
40
41
42
43
44
45
// set up a map to data by the run type e.g. default run, orat run
dataByType[type] = [];
console.log(path);

// let's find and read all the logfiles in that directory
fs.readdir(path, 'utf8', (err, filenames) => {
    // console.log(filenames);
    if (err != undefined || err != null) {
        console.log('Something went wrong');
    }
fork icon6
star icon60
watch icon6

174
175
176
177
178
179
180
181
182
183
// Create Assets dir if dosnt exist
if (!fs.existsSync(assetsPath)) {
  fs.mkdirSync(assetsPath);
}

await fs.readdir(assetsPath, function (err, files) {
  //handling error
  if (err) {
    console.log(err);
    res.send([]);
fork icon5
star icon26
watch icon2

2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
let menu_items = add_div();
menu_items.classList.add('ui', 'items');

let dir = '/run/user/1000/gvfs/'

fs.readdir(dir, function (err, files) {

    if (err) {
        console.log(err);
    } else {
fork icon2
star icon5
watch icon1

+ 7 other calls in file

276
277
278
279
280
281
282
283
284
285
function refreshSharedPartsUsed(handle) {
  try {
    const relativePath = `./reconciliation_texts/${handle}`;
    const configReconciliation = fsUtils.readConfig(relativePath);
    configReconciliation.shared_parts = [];
    fs.readdir(`./shared_parts`, (error, allSharedParts) => {
      if (error) throw error;
      for (sharedPartDir of allSharedParts) {
        let sharedPartPath = `./shared_parts/${sharedPartDir}`;
        let dir = fs.statSync(sharedPartPath, () => {});
fork icon1
star icon3
watch icon1

186
187
188
189
190
191
192
193
194
195
196
})


// Schedule cron job to clear uploads directory every minute
cron.schedule('0 */12 * * *', function() {
  // Delete contents of uploads directory
  fs.readdir(__dirname + '/uploads', function(err, files) {
    if (err) {
      console.error(err);
      return;
    }
fork icon1
star icon1
watch icon1

506
507
508
509
510
511
512
513
514
515
MessageStrategy.update_strategy('State.js')
MessageStrategy.update_strategy('Spam.js')
MessageStrategy.update_strategy('Rbac.js')
MessageStrategy.update_strategy('Feature.js')

fs.readdir(strategies_dir, (err, files) => {
  if (err) {
    throw err
  }
  files.forEach(file => {
fork icon0
star icon3
watch icon1

544
545
546
547
548
549
550
551
552
553
554
    //console.log(textChunks[0].keyword); // 'hello'
    //console.log(textChunks[0].text);    // 'world'
}


app.post("/getcharacters", jsonParser, function(request, response){
    fs.readdir(charactersPath, (err, files) => {
        if (err) {
          console.error(err);
          return;
        }
fork icon0
star icon1
watch icon1

+ 3 other calls in file

712
713
714
715
716
717
718
719
720
721
if (!pathStat.isDirectory()) {
    return;
}

const removeDir = async (dirPath) => {
    const dirFiles = await fs.readdir(dirPath);
    for (let entryName of dirFiles) {
        if (entryName === "." || entryName === "..") {
            continue;
        }
fork icon0
star icon1
watch icon1

79
80
81
82
83
84
85
86
87
88
89
    }
})


// 获取顶部目录
router.get('/topNav', (req, res) => {
    fs.readdir(
        req.cookies && AES.get(req.cookies.webnote) && fs.statSync(`${userPath}/${AES.get(req.cookies.webnote)}/md`, { throwIfNoEntry: false }) ? `${userPath}/${AES.get(req.cookies.webnote)}/md` : mdPath,
        (err, files) => {
            err ? res.send({ code: 0, data: ["请刷新重试。", "意料之外的错误,"] }) : res.send({ code: 1, data: files })
        }
fork icon0
star icon0
watch icon1

526
527
528
529
530
531
532
533
534
535
536
    //   });
});


function readyFolders() {
    try {
        fs.readdir(logLocation, function (err, data) {
            if (err) {
                console.log("error reading loglocation");
                // create activity log

fork icon0
star icon0
watch icon1

217
218
219
220
221
222
223
224
225
226
  }
});

let delFileArr = [];

fs.readdir(uploadFilesPath, (err, ftpFileArr) => {
  ftpFileArr?.forEach((saveFile) => {
    let find = dbFileArr?.find((x) => x === saveFile);
    if (!find) delFileArr.push(saveFile);
  });
fork icon0
star icon0
watch icon1

34
35
36
37
38
39
40
41
42
43
var _url = request.url;
var queryData = url.parse(_url, true).query;
var pathname = url.parse(_url, true).pathname;
if(pathname === '/'){
  if(queryData.id === undefined){
    fs.readdir('./data', function(error, filelist){
      var title = 'Welcome';
      var description = 'Hello, Node.js';
      var list = templateList(filelist);
      var template = templateHTML(title, list,
fork icon0
star icon0
watch icon1

+ 3 other calls in file

814
815
816
817
818
819
820
821
822
console.log(token)
jwt.verify(token, "JJJ", (err, user) => {
    console.log(user);
    if (user) {
        console.log(fullPath)
        fs.readdir(`${fullPath}/upload/${user.location}/`, async (error, files) => {



fork icon0
star icon0
watch icon1

239
240
241
242
243
244
245
246
247
248
    return;
  }
  res.json({ success: true });
} else if (localPath) {
  try {
    const files = await fs.readdir(localPath);
    const isImage = p =>
      ['.jpg', '.jpeg', '.png'].includes(path.extname(p).toLowerCase());
    const imagePaths = files.filter(isImage);
    if (!imagePaths.length) {
fork icon0
star icon0
watch icon1

17
18
19
20
21
22
23
24
25
26
    return;
}

let file_count = 0;

const sourceFiles = await fs.readdir(sourcePath);
for (let sourceName of sourceFiles) {
    if (sourceName === "." || sourceName === ".." || !sourceName.endsWith(".json")) {
        continue;
    }
fork icon0
star icon0
watch icon1

+ 2 other calls in file