fs.readdir ignore directories

北慕城南 提交于 2020-08-01 10:47:06

问题


I would like to scan the folder, but ignore all the folders/directories that are included in it. All I have in the (C:/folder/) are .txt files and other folders, I just want to scan the txt files, and ignore the folders.

app.get('/generatE', function (req, res) {
  const logsFolder = 'C:/folder/';
  fs.readdir(logsFolder, (err, files) => {
    if (err) {
      res.send("[empty]");
      return;
     }
     var lines = [];
     files.forEach(function(filename) {
       var logFileLines = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");

       logFileLines.forEach(function(logFileLine) {


         if(logFileLine.match(/.*AUDIT*./)) {
           lines.push(logFileLine+'\n');
         }
       })
     })

回答1:


Use fs.readdir or fs.readdirSync method with options { withFileTypes: true } and then do filtration using dirent.isFile (requires Node 10.10+).

Sync version

const fs = require('fs');
const dirents = fs.readdirSync(DIRECTORY_PATH, { withFileTypes: true });
const filesNames = dirents
    .filter(dirent => dirent.isFile())
    .map(dirent => dirent.name);
// use filesNames

Async version (with async/await, requires Node 11+)

import { promises as fs } from 'fs';

async function listFiles(directory) {
    const dirents = await fs.readdir(directory, { withFileTypes: true });
    return dirents
        .filter(dirent => dirent.isFile())
        .map(dirent => dirent.name);
}

Async version (with callbacks)

const fs = require('fs');
fs.readdir(DIRECTORY_PATH, { withFileTypes: true }, (err, dirents) => {
    const filesNames = dirents
        .filter(dirent => dirent.isFile())
        .map(dirent => dirent.name);
    // use filesNames
});



回答2:


Please See diraria's answer as it is more complete: my answer only works if ALL filenames contain a '.txt' extension.

why not just filter out files that end in ".txt"?

var fs = require("fs")
fs.readdirSync("./").filter(function(file) {
    if(file.indexOf(".txt")>-1)console.log(file)
})

I should have added previously that to get an array of these files you need to return them to an array as shown below.

var fs = require("fs")
let text_file_array = fs.readdirSync("./").filter(function(file) {
    if(file.indexOf(".txt")>-1) return file;
})


来源:https://stackoverflow.com/questions/41472161/fs-readdir-ignore-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!