Comprehensive Guide to Using Filehound for File Searching in NodeJS

Introduction to Filehound

Filehound is a powerful module in Node.js for searching files in directories with ease. It offers a wide range of APIs to help you filter and locate files based on a variety of criteria. In this guide, we will explore several useful APIs provided by Filehound along with code snippets and a comprehensive application example.

Installing Filehound

  
  npm install filehound
  

Basic File Search

Search for all files in a directory:

  
  const FileHound = require('filehound');

  FileHound.create()
    .paths('./path/to/directory')
    .find()
    .then(files => {
      console.log(files);
    });
  

Filter by Extension

Search for files with specific extensions:

  
  FileHound.create()
    .ext('js')
    .find()
    .then(files => {
      console.log(files);
    });
  

Filter by File Name

Search for files with specific names:

  
  FileHound.create()
    .match('example.js')
    .find()
    .then(files => {
      console.log(files);
    });
  

Find Files by Size

Search for files larger than a specific size:

  
  FileHound.create()
    .largerThan('1MB')
    .find()
    .then(files => {
      console.log(files);
    });
  

Find Files Based on Age

Search for files modified within the last 7 days:

  
  const daysSince = 7;
  FileHound.create()
    .modified(`>${daysSince}`)
    .find()
    .then(files => {
      console.log(files);
    });
  

Combining Multiple Filters

Using multiple filters together:

  
  FileHound.create()
    .paths('./path/to/directory')
    .ext('txt')
    .largerThan('1KB')
    .find()
    .then(files => {
      console.log(files);
    });
  

Application Example: Directory Cleaner

Let’s create a simple application that cleans up a directory by moving all files older than 30 days to an “archive” folder:

  
  const FileHound = require('filehound');
  const fs = require('fs');
  const path = require('path');

  const sourceDir = './path/to/directory';
  const archiveDir = './path/to/archive';

  if (!fs.existsSync(archiveDir)) {
    fs.mkdirSync(archiveDir);
  }

  FileHound.create()
    .paths(sourceDir)
    .modified('>30')
    .find()
    .then(files => {
      files.forEach(file => {
        const dest = path.join(archiveDir, path.basename(file));
        fs.rename(file, dest, (err) => {
          if (err) throw err;
          console.log(`Moved: ${file} to ${dest}`);
        });
      });
    })
    .catch(err => console.error('Error:', err));
  

This application searches for files older than 30 days in the specified directory and moves them to the archive folder.

Hash: 32616cdd0496509e2a2feb26c69d9b73255b10775e3c8e075d546195a94272c4

Leave a Reply

Your email address will not be published. Required fields are marked *