首页 > 解决方案 > Nodejs:搜索包含特定单词的文件夹

问题描述

我正在做一个项目,想要搜索并显示包含特定单词的所有文件夹的列表(不区分大小写)。我只想搜索和显示文件夹,而不是其中的内容或任何其他文件。我怎样才能做到这一点?我试过这样做,但无法弄清楚。

这是我的代码:

router.get('/displayDirectories', (req, res) => {

    const fs = require("fs");
    const userID = req.query.id;

    fs.access(`C:/Traning/${userID}`, function(err) {
    if(!err)
    {
       console.log("Directory exists");
       //this only prints if I enter the exact full name of the folder
       //I also want to add those directories in an array
    }
    else
    {
       console.log("Directory does not exist");
    }
 })

});

任何帮助,将不胜感激。

标签: node.jsexpress

解决方案


你的问题对我来说听起来不是很清楚(特别是如果你正在寻找一个或多个文件),但关于我的理解,我希望能帮助你

const { readdir } = require("fs");
const { join } = require('path')


router.get('/displayDirectories', (req, res) => {

    const userID = req.query.id;
    const thePath = join('C:/Traning', userID)    

    readdir(thePath, (e,d) => {
        if(e) {
            console.log('err parsing the directory: ', e)
            return
        }
        else {
            const list = []

            // set all file's name to lowercase
            const fileLowerCase = d.map(f => f.toLowerCase())
         
            const files = new Set(fileLowerCase)
            // if many files(userIdx) to check: iterate them
            // lowercase the researched file for case insensitive
            if (files.has(userId.toLowerCase()) === true) list.push(userId)
            // another check for ex
            if (files.has(userId2.toLowerCase()) === true) list.push(userId2)
                 
            if(list.length === 0) console.log('directories does not exist')
            else console.log('the matched directories are: ',list)
        }    
    }) 
    
});

第一个解决方案的问题是匹配文件的列表(在列表数组中)将是小写的。第二个问题是 Set 对象应该获得唯一的值,但是使用 .toLowerCase() 我们不再确定。

请参阅解决这两个问题的第二个解决方案。

  const { readdir } = require("fs");
   const { join } = require('path')
             
   router.get('/displayDirectories', (req, res) => {
        const userID = req.query.id;
        const thePath = join('C:/Traning', userID)    
        
        readdir(thePath, (e,d) => {
                if(e) {
                    console.log('err parsing the directory: ', e)
                    return
                }
                else {
    
                    // set all file's name to lowercase & match them to the target 
                    const list = d.map((f,i) => {
                      if(f.toLowerCase() === userID.toLowerCase()) return f                   
                    })
                        
                    if(list.length === 0) console.log('directories does not exist')
                    else console.log('the matched directories are: ',list)
        
                }    
            }) 
   });

推荐阅读