simple-folder-search 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,12 +10,6 @@ To install the package, use the following command:
10
10
  npm install simple-folder-search
11
11
  ```
12
12
 
13
- You can also install it using yarn:
14
-
15
- ```bash
16
- yarn add simple-folder-search
17
- ```
18
-
19
13
  ## Usage
20
14
 
21
15
  Here is a basic example of how to use the package:
package/package.json CHANGED
@@ -1,46 +1,60 @@
1
- {
2
- "name": "simple-folder-search",
3
- "version": "2.3.0",
4
- "description": "A simple folder search package",
5
- "main": "dist/index.cjs",
6
- "exports": {
7
- "import": "./dist/index.mjs",
8
- "require": "./dist/index.cjs"
9
- },
10
- "type": "module",
11
- "scripts": {
12
- "test": "echo \"Error: no test specified\" && exit 1",
13
- "build": "tsup src/index.ts --format esm,cjs --dts --out-dir dist",
14
- "code": "git pull && npm i && code . && eslint src",
15
- "c": "npm run code"
16
- },
17
- "author": "iTsMaaT",
18
- "license": "MIT",
19
- "repository": {
20
- "type": "git",
21
- "url": "git+https://github.com/iTsMaaT/simple-folder-search.git"
22
- },
23
- "bugs": {
24
- "url": "https://github.com/iTsMaaT/simple-folder-search.git"
25
- },
26
- "homepage": "https://github.com/iTsMaaT/simple-folder-search.git",
27
- "keywords": [
28
- "folder",
29
- "file",
30
- "search",
31
- "find"
32
- ],
33
- "devDependencies": {
34
- "@types/node": "^22.10.2",
35
- "@typescript-eslint/eslint-plugin": "^8.18.1",
36
- "@typescript-eslint/parser": "^8.18.1",
37
- "eslint": "^9.17.0",
38
- "globals": "^15.13.0",
39
- "tsup": "^8.3.5",
40
- "tsx": "^4.19.2",
41
- "typescript": "^5.7.2"
42
- },
43
- "dependencies": {
44
- "fuse.js": "^7.0.0"
45
- }
46
- }
1
+ {
2
+ "name": "simple-folder-search",
3
+ "version": "2.3.1",
4
+ "description": "A simple folder search package",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.cts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.cts",
16
+ "default": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "type": "module",
25
+ "scripts": {
26
+ "test": "echo \"Error: no test specified\" && exit 1",
27
+ "build": "tsup",
28
+ "code": "git pull && npm i && code . && eslint src",
29
+ "c": "npm run code"
30
+ },
31
+ "author": "iTsMaaT",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/iTsMaaT/simple-folder-search.git"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/iTsMaaT/simple-folder-search.git"
39
+ },
40
+ "homepage": "https://github.com/iTsMaaT/simple-folder-search.git",
41
+ "keywords": [
42
+ "folder",
43
+ "file",
44
+ "search",
45
+ "find"
46
+ ],
47
+ "devDependencies": {
48
+ "@types/node": "^22.10.2",
49
+ "@typescript-eslint/eslint-plugin": "^8.18.1",
50
+ "@typescript-eslint/parser": "^8.18.1",
51
+ "eslint": "^9.17.0",
52
+ "globals": "^15.13.0",
53
+ "tsup": "^8.3.5",
54
+ "tsx": "^4.19.2",
55
+ "typescript": "^5.7.2"
56
+ },
57
+ "dependencies": {
58
+ "fuse.js": "^7.0.0"
59
+ }
60
+ }
package/docs/caching.md DELETED
@@ -1,102 +0,0 @@
1
- # Custom Caching
2
-
3
- The Simple Folder Search package supports custom caching to improve search performance. You can provide a custom caching method to the `simpleFolderSearch` function using a callback. This allows you to use different caching mechanisms, such as an in-memory cache or a database.
4
-
5
- ## In-Memory Cache Example
6
-
7
- ```javascript
8
- const cache = {};
9
-
10
- async function inMemoryCacheCallback(filePath, fileExtensions) {
11
- if (cache[filePath]) {
12
- return cache[filePath];
13
- }
14
-
15
- // Default file collection logic
16
- const files = [];
17
- function collectFiles(dir) {
18
- const entries = fs.readdirSync(dir, { withFileTypes: true });
19
- for (const entry of entries) {
20
- const fullPath = path.join(dir, entry.name);
21
- if (entry.isDirectory()) {
22
- collectFiles(fullPath);
23
- } else if (fileExtensions.length === 0 || fileExtensions.some(ext => entry.name.endsWith(ext))) {
24
- files.push(fullPath);
25
- }
26
- }
27
- }
28
-
29
- collectFiles(filePath);
30
- cache[filePath] = files;
31
- return files;
32
- }
33
-
34
- const results = await simpleFolderSearch("./music", [".mp3", ".wav"], "my song", { minimumScore: 0.6, batchSize: 100 }, inMemoryCacheCallback);
35
- console.log(results);
36
- ```
37
-
38
- ## Database Cache Example
39
-
40
- You can use a lightweight database like SQLite for caching.
41
-
42
- 1. Install SQLite:
43
-
44
- ```bash
45
- npm install sqlite3
46
- ```
47
-
48
- 2. Indexing Files: Create a script to index files and store them in the database.
49
-
50
- ```js
51
- const sqlite3 = require('sqlite3').verbose();
52
- const db = new sqlite3.Database('files.db');
53
-
54
- db.serialize(() => {
55
- db.run("CREATE TABLE IF NOT EXISTS files (name TEXT, path TEXT, extension TEXT)");
56
-
57
- const indexFiles = (dir) => {
58
- const entries = fs.readdirSync(dir, { withFileTypes: true });
59
- for (const entry of entries) {
60
- const fullPath = path.join(dir, entry.name);
61
- if (entry.isDirectory()) {
62
- indexFiles(fullPath);
63
- } else {
64
- const ext = path.extname(entry.name);
65
- db.run("INSERT INTO files (name, path, extension) VALUES (?, ?, ?)", [entry.name, fullPath, ext]);
66
- }
67
- }
68
- };
69
-
70
- indexFiles("./your-directory");
71
- });
72
-
73
- db.close();
74
- ```
75
-
76
- 3. Database Cache Callback: Implement the cache callback to fetch files from the database.
77
-
78
- This method also pre-checks the search to filter words out of the database results, as the database searches much faster than fuzzy-matching
79
-
80
- ```js
81
- const sqlite3 = require('sqlite3').verbose();
82
- const db = new sqlite3.Database('files.db');
83
-
84
- async function dbCacheCallback(filePath, fileExtensions) {
85
- return new Promise((resolve, reject) => {
86
- const exts = fileExtensions.map(() => '?').join(',');
87
- const tokens = (!search ? '1=1' : Array.isArray(search) ? search.join(' '): search).toLowerCase().split(' ').map(x => 'path LIKE "%'+x+'%"').join(' OR ');
88
- db.all("SELECT path FROM files WHERE extension IN (" + exts + ") AND (" + tokens + ")", fileExtensions, (err, rows) => {
89
- if (err) {
90
- reject(err);
91
- } else {
92
- resolve(rows.map(row => row.path));
93
- }
94
- });
95
- });
96
- }
97
-
98
- const results = await simpleFolderSearch("./music", [".mp3", ".wav"], "my song", { minimumScore: 0.6, batchSize: 100 }, dbCacheCallback);
99
- console.log(results);
100
- ```
101
-
102
- This approach allows you to customize the caching mechanism according to your needs, whether it's an in-memory cache, a database, or any other storage solution.
package/docs/index.md DELETED
@@ -1,11 +0,0 @@
1
- # Simple Folder Search Documentation
2
-
3
- Welcome to the Simple Folder Search documentation. This package provides a simple way to search for files within a folder. It is designed to be easy to use and integrate into your projects.
4
-
5
- ## Table of Contents
6
-
7
- - [Installation](installation.md)
8
- - [Usage](usage.md)
9
- - [Options](options.md)
10
- - [Custom Caching](caching.md)
11
- - [Types](types.md)
@@ -1,13 +0,0 @@
1
- # Installation
2
-
3
- To install the package, use the following command:
4
-
5
- ```bash
6
- npm install simple-folder-search
7
- ```
8
-
9
- You can also install it using yarn:
10
-
11
- ```bash
12
- yarn add simple-folder-search
13
- ```
package/docs/options.md DELETED
@@ -1,21 +0,0 @@
1
- # Options
2
-
3
- The Simple Folder Search package provides several options to customize the search behavior. Here are the available options:
4
-
5
- ## minimumScore
6
-
7
- - **Type:** `number`
8
- - **Default:** `0.6`
9
- - **Description:** The minimum score required for a file to be considered a match.
10
-
11
- ## batchSize
12
-
13
- - **Type:** `number`
14
- - **Default:** `100`
15
- - **Description:** The number of files to process in each batch.
16
-
17
- ## parallelSearches
18
-
19
- - **Type:** `number`
20
- - **Default:** `1`
21
- - **Description:** The number of parallel searches to perform.
package/docs/types.md DELETED
@@ -1,32 +0,0 @@
1
- # Types
2
-
3
- This document describes the types used in the Simple Folder Search package.
4
-
5
- ## SearchOptions
6
-
7
- ```typescript
8
- interface SearchOptions {
9
- minimumScore?: number;
10
- batchSize?: number;
11
- parallelSearches?: number;
12
- }
13
- ```
14
-
15
- ## CacheCallback
16
-
17
- A callback function type for custom caching logic.
18
-
19
- ```ts
20
- type CacheCallback = (filePath: string, fileExtensions: string[], search?: string[] | string) => Promise<string[]>;
21
- ```
22
-
23
- ## SearchResult
24
-
25
- ```ts
26
- interface SearchResult {
27
- filePath: string;
28
- score: number;
29
- }
30
- ```
31
-
32
- These types are used to define the options for the search and the structure of the search results.
package/docs/usage.md DELETED
@@ -1,55 +0,0 @@
1
- # Usage
2
-
3
- Here is an example of how to use the package to search for files and play a file using `discord-player`'s search method:
4
-
5
- ```javascript
6
- const { simpleFolderSearch } = require('simple-folder-search');
7
- const { Player, QueryType } = require('discord-player');
8
-
9
- // Initialize the player
10
- const player = new Player(client);
11
-
12
- // Search for music files in your music folder
13
- const musicFiles = await simpleFolderSearch('./music', ['.mp3', '.wav'], 'my song', { minimumScore: 0.6 });
14
-
15
- if (musicFiles.length > 0) {
16
- // Get the first matching file
17
- const firstMatch = musicFiles[0];
18
-
19
- // Search the track using the proper engine
20
- const research = player.search(firstMatch, {
21
- searchEngine: QueryType.FILE,
22
- });
23
-
24
- // Play the file using discord-player
25
- await player.play(voiceChannel, research);
26
- } else {
27
- console.log('No matching files found');
28
- }
29
- ```
30
-
31
- ## Searching by Name and Artist
32
-
33
- You can also search for files using both the file name and the artist (folder name) by providing the search query as an array. The first element of the array should be the file name, and the second element should be the artist (folder name).
34
-
35
- ```js
36
- const results = await simpleFolderSearch("./music", [".mp3", ".wav"], ["my song", "artist name"], { minimumScore: 0.6, batchSize: 100 });
37
- console.log(results);
38
- ```
39
-
40
- In this example, the search will look for files named "my song" within folders named "artist name".
41
-
42
- ## Advanced Usage
43
-
44
- ```js
45
- const options = {
46
- minimumScore: 0.7,
47
- batchSize: 50,
48
- parallelSearches: 5,
49
- };
50
-
51
- const advancedResults = await simpleFolderSearch("./music", [".mp3", ".wav"], "advanced search", options);
52
- console.log(advancedResults);
53
- ```
54
-
55
- In this example, the search will look for files with a minimum score of 0.7, process 50 files at a time and perform 5 parallel searches.
package/eslint.config.mjs DELETED
@@ -1,106 +0,0 @@
1
- import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
- import tsParser from "@typescript-eslint/parser";
3
- import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import js from "@eslint/js";
6
- import { FlatCompat } from "@eslint/eslintrc";
7
-
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = path.dirname(__filename);
10
- const compat = new FlatCompat({
11
- baseDirectory: __dirname,
12
- recommendedConfig: js.configs.recommended,
13
- allConfig: js.configs.all
14
- });
15
-
16
- export default [...compat.extends(
17
- "eslint:recommended",
18
- "plugin:@typescript-eslint/recommended",
19
- //"plugin:@typescript-eslint/recommended-requiring-type-checking",
20
- ), {
21
- ignores: [
22
- "dist/*",
23
- "node_modules",
24
- "eslint.config.mjs",
25
- "tsup.config.ts",
26
- "tinker.ts",
27
- "tinker.js"
28
- ],
29
- plugins: {
30
- "@typescript-eslint": typescriptEslint,
31
- },
32
- languageOptions: {
33
- parser: tsParser,
34
- ecmaVersion: 2023,
35
- sourceType: "module",
36
-
37
- parserOptions: {
38
- project: "./tsconfig.json",
39
- },
40
- },
41
-
42
- rules: {
43
- "@typescript-eslint/no-unused-vars": "off",
44
- "@typescript-eslint/no-require-imports": "off",
45
- indent: ["error", 4, {
46
- SwitchCase: 1,
47
- }],
48
-
49
- semi: "error",
50
- "prefer-const": "error",
51
- "no-undef": "off",
52
- "no-unused-vars": "off",
53
-
54
- "arrow-spacing": ["warn", {
55
- before: true,
56
- after: true,
57
- }],
58
-
59
- "comma-dangle": ["error", "always-multiline"],
60
- "comma-spacing": "error",
61
- "comma-style": "error",
62
- curly: ["error", "multi-or-nest", "consistent"],
63
- "dot-location": ["error", "property"],
64
- "handle-callback-err": "off",
65
- "keyword-spacing": "error",
66
-
67
- "max-nested-callbacks": ["error", {
68
- max: 3,
69
- }],
70
-
71
- "max-statements-per-line": ["error", {
72
- max: 3,
73
- }],
74
-
75
- "no-console": "off",
76
- "no-empty-function": "error",
77
- "no-floating-decimal": "error",
78
- "no-lonely-if": "error",
79
-
80
- "no-multiple-empty-lines": ["error", {
81
- max: 2,
82
- maxEOF: 1,
83
- maxBOF: 0,
84
- }],
85
-
86
- "no-shadow": ["error", {
87
- allow: ["err", "error", "e", "resolve", "reject", "buffer"],
88
- }],
89
-
90
- "no-var": "error",
91
- "object-curly-spacing": ["error", "always"],
92
- quotes: ["error", "double"],
93
- "space-before-blocks": "error",
94
-
95
- "space-before-function-paren": ["error", {
96
- anonymous: "never",
97
- named: "never",
98
- asyncArrow: "always",
99
- }],
100
-
101
- "space-in-parens": "error",
102
- "space-infix-ops": "error",
103
- "spaced-comment": "error",
104
- yoda: "error",
105
- },
106
- }];
package/src/index.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./simple-folder-search";
@@ -1,124 +0,0 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import Fuse from "fuse.js";
4
-
5
- type CacheCallback = (filePath: string, fileExtensions: string[], search?: string[] | string) => Promise<string[]>;
6
-
7
- interface SearchOptions {
8
- minimumScore?: number;
9
- batchSize?: number;
10
- parallelSearches?: number;
11
- }
12
-
13
- /**
14
- * Perform a simple folder search based on file names and optionally artist names.
15
- *
16
- * @param {string} filepath - The directory to search in.
17
- * @param {string[]} fileExtensions - An array of file extensions to filter by.
18
- * @param {string | string[]} search - The search query, either a string or an array of [name, artist].
19
- * @param {SearchOptions} [options] - Optional search options.
20
- * @param {CacheCallback} [cacheCallback] - Optional callback for custom caching logic.
21
- * @returns {Promise<string[]>} A promise that resolves to an array of file paths that match the search query.
22
- */
23
- export async function simpleFolderSearch(
24
- filepath: string,
25
- fileExtensions: string[],
26
- search: string | string[],
27
- options: SearchOptions = {},
28
- cacheCallback?: CacheCallback,
29
- ): Promise<string[]> {
30
- const {
31
- minimumScore = 0.6,
32
- batchSize = 100,
33
- parallelSearches = 1,
34
- } = options;
35
-
36
- const absolutePath = path.resolve(process.cwd(), filepath);
37
-
38
- if (!fs.existsSync(absolutePath)) throw new Error("Filepath does not exist.");
39
- if (!Array.isArray(fileExtensions)) throw new Error("fileExtensions must be an array.");
40
- if (typeof search !== "string" && !Array.isArray(search)) throw new Error("Search query must be a string or an array.");
41
- if (typeof minimumScore !== "number") throw new Error("Minimum score must be a number.");
42
- if (minimumScore < 0 || minimumScore > 1) throw new Error("Minimum score must be between 0 and 1.");
43
- if (typeof batchSize !== "number" || batchSize <= 0) throw new Error("Batch size must be a positive number.");
44
- if (typeof parallelSearches !== "number" || parallelSearches <= 0) throw new Error("Parallel searches must be a positive number.");
45
-
46
- const filesForFuse: { name: string; artist?: string; path: string}[] = [];
47
-
48
- const processFiles = async (files: string[]) => {
49
- for (const file of files) {
50
- const fileData: { name: string; artist?: string; path: string} = {
51
- name: path.parse(file).name,
52
- artist: path.basename(path.dirname(file)),
53
- path: file,
54
- };
55
-
56
- filesForFuse.push(fileData);
57
- }
58
- };
59
-
60
- if (cacheCallback) {
61
- const cachedFiles = await cacheCallback(absolutePath, fileExtensions, search);
62
- await processFiles(cachedFiles);
63
- } else {
64
- function* collectFiles(dir: string): Generator<string[]> {
65
- const entries = fs.readdirSync(dir, { withFileTypes: true });
66
- let batch: string[] = [];
67
-
68
- for (const entry of entries) {
69
- const fullPath = path.join(dir, entry.name);
70
- if (entry.isDirectory()) {
71
- yield* collectFiles(fullPath);
72
- } else if (fileExtensions.length == 0 || fileExtensions.some(ext => entry.name.endsWith(ext))) {
73
- batch.push(fullPath);
74
- if (batch.length >= batchSize) {
75
- yield batch;
76
- batch = [];
77
- }
78
- }
79
- }
80
-
81
- if (batch.length > 0)
82
- yield batch;
83
- }
84
-
85
- for (const batch of collectFiles(absolutePath))
86
- await processFiles(batch);
87
-
88
- }
89
-
90
- // If search is empty, return all files with matching extensions
91
- if (!search || (Array.isArray(search) && search.length === 0))
92
- return filesForFuse.map(file => file.path);
93
-
94
- return await searchCandidates(filesForFuse, search, minimumScore);
95
- }
96
-
97
- /**
98
- * Search for candidates based on a search query and minimum score.
99
- *
100
- * @param {Array<{name: string; artist?: string; path: string;}>} candidates - An array of candidate objects to search through.
101
- * @param {string | string[]} search - The search query, either a string or an array of [name, artist].
102
- * @param {number} minimumScore - The minimum score required for a candidate to be considered a match.
103
- * @returns {Promise<string[]>} A promise that resolves to an array of file paths that match the search query.
104
- */
105
- export async function searchCandidates(candidates: {name: string; artist?: string; path: string;}[], search: string|string[], minimumScore: number): Promise<string[]> {
106
- // Setup Fuse with options
107
- const fuseOptions = {
108
- includeScore: true,
109
- threshold: 1 - minimumScore, // Convert our score to Fuse threshold
110
- keys: ["name", "artist"],
111
- };
112
- const fuse = new Fuse(candidates, fuseOptions);
113
-
114
- // Perform search and filter results
115
- const searchQueries = Array.isArray(search) ? [{ name: search[0], artist: search[1] }] : [search];
116
- const searchPromises = searchQueries.map(query => fuse.search(query));
117
-
118
- const results = await Promise.all(searchPromises);
119
- const flattenedResults = results.flat();
120
-
121
- return flattenedResults
122
- .filter(result => (result.score ? result.score <= (1 - minimumScore) : false))
123
- .map(result => result.item.path);
124
- }
package/tsup.config.ts DELETED
@@ -1,9 +0,0 @@
1
- import { defineConfig } from "tsup"
2
-
3
- export default defineConfig({
4
- format: ["esm","cjs"],
5
- entry: ['./src/index.ts'],
6
- outDir: "./dist",
7
- skipNodeModulesBundle: true,
8
- dts: true
9
- });