@1-/scan 0.1.10 → 0.1.11

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
@@ -3,108 +3,84 @@
3
3
  ---
4
4
 
5
5
  <a id="en"></a>
6
- # @1-/scan : SQLite-backed incremental directory file scanner
7
-
8
- - [@1-/scan : SQLite-backed incremental directory file scanner](#1-scan-sqlite-backed-incremental-directory-file-scanner)
9
- - [1. Features](#1-features)
10
- - [2. Usage](#2-usage)
11
- - [Basic Incremental Scan](#basic-incremental-scan)
12
- - [Bulk Storage Module](#bulk-storage-module)
13
- - [3. Design](#3-design)
14
- - [4. Tech Stack](#4-tech-stack)
15
- - [5. Code Structure](#5-code-structure)
16
- - [6. History](#6-history)
6
+ # scan : Efficient file system scanning and change detection
7
+
8
+ - [scan : Efficient file system scanning and change detection](#scan-efficient-file-system-scanning-and-change-detection)
9
+ - [Functionality](#functionality)
10
+ - [Usage demonstration](#usage-demonstration)
11
+ - [Design rationale](#design-rationale)
12
+ - [Technology stack](#technology-stack)
13
+ - [Code structure](#code-structure)
14
+ - [Historical context](#historical-context)
17
15
  - [About](#about)
18
16
 
19
- Incrementally scans directory files, compares file sizes and modification times to detect changes, synchronizes metadata to SQLite database, and returns list of changed relative paths.
17
+ ## Functionality
20
18
 
21
- ## 1. Features
19
+ This utility scans directories to detect file changes by comparing current file metadata against cached records. It tracks file size, modification time, and MD5 hashes to identify additions, modifications, and deletions efficiently.
22
20
 
23
- - **Incremental Scan**: Compares size and modification time, filtering unchanged files to reduce disk I/O.
24
- - **Key Length Optimization**: Stores raw bytes for paths up to 16 bytes. Converts longer paths into 16-byte MD5 hashes to optimize database index space and query performance.
25
- - **Memory Optimization**: Uses BinMap and BinSet to store binary keys in memory, avoiding string decoding overhead and reducing memory footprint.
26
- - **Transactional Integrity**: Performs metadata updates and deletions in database transactions to ensure consistency.
27
- - **Auto Configuration**: Integrates @1-/sqlite to initialize database schema and manage database connections automatically, updating .gitignore when new database is detected.
21
+ The system uses binary data structures for memory efficiency and supports concurrent scanning with automatic parallelism adjustment based on available CPU cores.
28
22
 
29
- ## 2. Usage
23
+ ## Usage demonstration
30
24
 
31
- ### Basic Incremental Scan
25
+ Install as a dependency:
32
26
 
33
- ```javascript
34
- import scan from "@1-/scan";
35
-
36
- const dir = "./data";
37
- const db_dir = "./db";
38
- const files = ["file1.txt", "file2.txt"];
39
-
40
- // Scan file list, sync metadata to SQLite, return changed relative paths and upsert function
41
- const [updated_paths, upsert] = await scan(dir, db_dir, files);
42
-
43
- // Close database automatically when exiting scope
44
- using _ = upsert;
45
-
46
- console.log("Updated files:", updated_paths);
47
-
48
- // Update scanned file metadata in database
49
- for (const rel_path of updated_paths) {
50
- await upsert(rel_path);
51
- }
27
+ ```bash
28
+ npm install @1-/scan
52
29
  ```
53
30
 
54
- ### Bulk Storage Module
31
+ Basic usage:
55
32
 
56
33
  ```javascript
57
- import save from "@1-/scan/save.js";
58
- import sqlite from "@1-/sqlite";
34
+ import scan from '@1-/scan';
59
35
 
60
- const db = sqlite("./scan_record.db");
36
+ // Scan directory and get update list
37
+ const [updateFiles, upsert] = await scan('/path/to/dir', '/path/to/db', ['file1.js', 'file2.json']);
61
38
 
62
- // Bulk update and delete metadata
63
- save(db, [["file.txt", new Uint8Array([1, 2, 3]), 123, 1620000000]], [new Uint8Array([4, 5, 6])]);
39
+ console.log('Files that need updating:', updateFiles);
64
40
 
65
- db.close();
41
+ // Save the updated metadata to database
42
+ await upsert();
66
43
  ```
67
44
 
68
- ## 3. Design
45
+ ## Design rationale
69
46
 
70
- Main entry orchestrates modules to scan directories and synchronize metadata.
47
+ The architecture prioritizes efficiency through several key design decisions:
71
48
 
72
- ![](https://fastly.jsdelivr.net/gh/webc-fs/-@PE/plI9PPJK-kcEku6PWdAg.svg)
49
+ - Binary data structures (BinSet, BinMap) minimize memory overhead
50
+ - Base64url encoding for path keys enables compact storage
51
+ - Concurrent scanning with dynamic parallelism limits
52
+ - Two-phase comparison: quick metadata check followed by expensive MD5 verification only when needed
53
+ - CSV-based persistent storage for simplicity and portability
73
54
 
74
- 1. **Initialize Connection**: Calls `@1-/sqlite` to open SQLite database. Updates `.gitignore` in the database directory if the database is newly created to prevent tracking.
75
- 2. **Load Records**: `load.js` checks and creates `scan` table. Reads stored paths, sizes, and modification times to restore memory mappings inside `BinMap`.
76
- 3. **Compare Files**: `scan.js` iterates over input file list, calling `stat.js` for metadata and utilizing `@1-/hash` to map paths to 16-byte binary keys. Adds files with mismatched size or modification time to change list.
77
- 4. **Delete and Return**: `rm.js` deletes absent or unscanned records in transaction. Returns changed paths list and `upsert` function (provided by `upsert.js`) for persistence, supporting automatic resource disposal.
55
+ ![](https://fastly.jsdelivr.net/gh/webc-fs/-@B4/0t9t7yVs82Pn-_d5eXrw.svg)
78
56
 
79
- ## 4. Tech Stack
57
+ ## Technology stack
80
58
 
81
- - **Bun**: Runtime environment and test framework.
82
- - **@1-/sqlite**: Database connection management and transaction wrapper.
83
- - **@1-/hash**: Length-bounded MD5 hash utility.
84
- - **@3-/vb**: Variable-length byte (Varint) encoder and decoder.
85
- - **@3-/binmap / @3-/binset**: Rust and WebAssembly binary key containers.
59
+ - Node.js runtime with modern ES modules
60
+ - Binary data structures: `@3-/binset`, `@3-/binmap`
61
+ - Base64url encoding: `@3-/base64url`
62
+ - File hashing: `@1-/md5`
63
+ - CSV processing: `@1-/csv`
64
+ - Gitignore management: `@1-/upsert_gitignore`
65
+ - Concurrency control: `@3-/plimit`
86
66
 
87
- ## 5. Code Structure
67
+ ## Code structure
88
68
 
89
- ```text
90
- .
91
- ├── src
92
- ├── _.js # Core controller flow
93
- ├── load.js # Table initialization and loading
94
- ├── rm.js # Batch deletion of metadata
95
- ├── save.js # Batch storage and updates
96
- ├── scan.js # Scans and compares files
97
- ├── stat.js # Retrieves file metadata and path hash
98
- └── upsert.js # Single-record updates and auto-dispose
99
- └── tests # Unit tests
69
+ ```
70
+ src/
71
+ ├── _.js # Main entry point and exports
72
+ ├── const.js # Constants (database filenames)
73
+ ├── dbInit.js # Database initialization and loading
74
+ ├── rm.js # File removal from database
75
+ ├── scan.js # Core scanning logic
76
+ ├── stat.js # File system statistics collection
77
+ ├── upsert.js # Database persistence logic
78
+ └── test/ # Test files
100
79
  ```
101
80
 
102
- ## 6. History
103
-
104
- SQLite was created by D. Richard Hipp in 2000 while designing board software for guided-missile destroyers. The system originally depended on commercial database that required constant database administration; connection loss could stall the entire damage control application. Hipp designed serverless, zero-configuration embedded database that directly reads and writes local files, marking the birth of SQLite.
105
-
106
- To conserve space and reduce latency, SQLite utilizes Varint (variable-length integer) encoding for metadata storage. Under this scheme, small integers consume only 1 byte, while larger numbers scale dynamically. This library inherits that design philosophy, compressing file metadata into varints for memory storage to ensure minimal footprint and high synchronization performance.
81
+ ## Historical context
107
82
 
83
+ File scanning utilities trace their origins to early Unix tools like `find` and `diff`. Modern implementations face new challenges with massive file systems and cloud storage. This implementation draws inspiration from incremental backup systems developed in the 1990s, which pioneered the two-phase comparison approach (quick metadata check followed by content verification) to balance speed and accuracy. The use of binary data structures reflects contemporary optimizations for memory-constrained environments and high-performance computing scenarios.
108
84
  ## About
109
85
 
110
86
  This library is developed by [WebC.site](https://webc.site).
@@ -115,108 +91,84 @@ This library is developed by [WebC.site](https://webc.site).
115
91
  ---
116
92
 
117
93
  <a id="zh"></a>
118
- # @1-/scan : 基于 SQLite 的目录文件增量扫描器
119
-
120
- - [@1-/scan : 基于 SQLite 的目录文件增量扫描器](#1-scan-基于-sqlite-的目录文件增量扫描器)
121
- - [1. 功能介绍](#1-功能介绍)
122
- - [2. 使用演示](#2-使用演示)
123
- - [基础增量扫描](#基础增量扫描)
124
- - [独立批量存储模块](#独立批量存储模块)
125
- - [3. 设计思路](#3-设计思路)
126
- - [4. 技术栈](#4-技术栈)
127
- - [5. 代码结构](#5-代码结构)
128
- - [6. 历史故事](#6-历史故事)
94
+ # scan : 高效的文件系统扫描与变更检测
95
+
96
+ - [scan : 高效的文件系统扫描与变更检测](#scan-高效的文件系统扫描与变更检测)
97
+ - [功能介绍](#功能介绍)
98
+ - [使用演示](#使用演示)
99
+ - [设计思路](#设计思路)
100
+ - [技术栈](#技术栈)
101
+ - [代码结构](#代码结构)
102
+ - [历史故事](#历史故事)
129
103
  - [关于](#关于)
130
104
 
131
- 增量扫描目录文件,比对文件大小与修改时间检测变更,同步元数据至 SQLite 数据库,返回已变更相对路径列表。
105
+ ## 功能介绍
132
106
 
133
- ## 1. 功能介绍
107
+ 本工具通过比对当前文件元数据与缓存记录,扫描目录以检测文件变更。系统跟踪文件大小、修改时间及MD5哈希值,高效识别新增、修改和删除操作。
134
108
 
135
- - **增量扫描**:比对大小与修改时间,过滤未变更文件,减少磁盘读写。
136
- - **键长优化**:路径长度不大于 16 字节时存储原始字节,超出 16 字节转换为 16 字节 MD5 值,优化索引空间与查询性能。
137
- - **内存优化**:使用 BinMap 与 BinSet 存储二进制键,避免字符串解码,降低内存占用。
138
- - **事务保障**:元数据变更与删除操作合并在数据库事务中执行,确保数据一致性。
139
- - **自动配置**:集成 @1-/sqlite,自动初始化数据库表结构,并在检测到新数据库时自动更新 .gitignore。
109
+ 采用二进制数据结构实现内存效率优化,并支持基于可用CPU核心数自动调整的并发扫描。
140
110
 
141
- ## 2. 使用演示
111
+ ## 使用演示
142
112
 
143
- ### 基础增量扫描
113
+ 安装为依赖项:
144
114
 
145
- ```javascript
146
- import scan from "@1-/scan";
147
-
148
- const dir = "./data";
149
- const db_dir = "./db";
150
- const files = ["file1.txt", "file2.txt"];
151
-
152
- // 扫描文件列表并同步至 SQLite,返回已变更的相对路径列表与更新函数
153
- const [updated_paths, upsert] = await scan(dir, db_dir, files);
154
-
155
- // 退出作用域自动关闭数据库
156
- using _ = upsert;
157
-
158
- console.log("更新文件列表:", updated_paths);
159
-
160
- // 更新已处理文件的元数据至数据库
161
- for (const rel_path of updated_paths) {
162
- await upsert(rel_path);
163
- }
115
+ ```bash
116
+ npm install @1-/scan
164
117
  ```
165
118
 
166
- ### 独立批量存储模块
119
+ 基础用法:
167
120
 
168
121
  ```javascript
169
- import save from "@1-/scan/save.js";
170
- import sqlite from "@1-/sqlite";
122
+ import scan from '@1-/scan';
171
123
 
172
- const db = sqlite("./scan_record.db");
124
+ // 扫描目录并获取更新列表
125
+ const [updateFiles, upsert] = await scan('/path/to/dir', '/path/to/db', ['file1.js', 'file2.json']);
173
126
 
174
- // 批量更新与删除元数据
175
- save(db, [["file.txt", new Uint8Array([1, 2, 3]), 123, 1620000000]], [new Uint8Array([4, 5, 6])]);
127
+ console.log('需要更新的文件:', updateFiles);
176
128
 
177
- db.close();
129
+ // 将更新后的元数据保存至数据库
130
+ await upsert();
178
131
  ```
179
132
 
180
- ## 3. 设计思路
133
+ ## 设计思路
181
134
 
182
- 主入口调度各模块,协作完成目录扫描与数据同步。
135
+ 架构设计优先考虑效率,关键决策包括:
183
136
 
184
- ![](https://fastly.jsdelivr.net/gh/webc-fs/-@Bb/xl59c_lSLj5HJBw9gJ3g.svg)
137
+ - 二进制数据结构(BinSet、BinMap)最小化内存开销
138
+ - 路径键使用base64url编码实现紧凑存储
139
+ - 并发扫描配合动态并行度限制
140
+ - 两阶段比对:快速元数据检查后仅在必要时执行耗时MD5验证
141
+ - 基于CSV的持久化存储确保简单性和可移植性
185
142
 
186
- 1. **初始化连接**:调用 `@1-/sqlite` 打开 SQLite 数据库。若数据库为新创建,自动更新所在目录的 `.gitignore` 阻断提交。
187
- 2. **加载记录**:`load.js` 检查并创建 `scan` 表。读取已记录的路径、大小及修改时间,恢复至内存映射 `BinMap` 中。
188
- 3. **比对文件**:`scan.js` 遍历输入文件列表,调用 `stat.js` 获取元数据,并利用 `@1-/hash` 将路径映射为 16 字节二进制键。比对大小或修改时间,差异项归入变更列表。
189
- 4. **删除与返回**:`rm.js` 在事务中批量删除物理移除或不再扫描的记录。返回变更路径列表与 `upsert` 函数(`upsert.js` 提供),用以更新数据库,支持自动释放。
143
+ ![](https://fastly.jsdelivr.net/gh/webc-fs/-@He/ywew0gcPy6M8EMHRuoHw.svg)
190
144
 
191
- ## 4. 技术栈
145
+ ## 技术栈
192
146
 
193
- - **Bun**:JavaScript 运行时与测试框架。
194
- - **@1-/sqlite**:SQLite 连接管理与事务封装。
195
- - **@1-/hash**:长度限制的 MD5 哈希工具。
196
- - **@3-/vb**:Varint 变长整型编码与解码器。
197
- - **@3-/binmap / @3-/binset**:基于 Rust 与 WebAssembly 的高效二进制键容器。
147
+ - Node.js运行时,支持现代ES模块
148
+ - 二进制数据结构:`@3-/binset`、`@3-/binmap`
149
+ - Base64url编码:`@3-/base64url`
150
+ - 文件哈希:`@1-/md5`
151
+ - CSV处理:`@1-/csv`
152
+ - Gitignore管理:`@1-/upsert_gitignore`
153
+ - 并发控制:`@3-/plimit`
198
154
 
199
- ## 5. 代码结构
155
+ ## 代码结构
200
156
 
201
- ```text
202
- .
203
- ├── src
204
- ├── _.js # 核心控制流程
205
- ├── load.js # 元数据表初始化与加载
206
- ├── rm.js # 批量删除元数据
207
- ├── save.js # 批量存储元数据
208
- ├── scan.js # 扫描与比对文件
209
- ├── stat.js # 获取文件元数据及路径哈希
210
- └── upsert.js # 逐个更新与自动关闭
211
- └── tests # 单元测试
157
+ ```
158
+ src/
159
+ ├── _.js # 主入口点及导出
160
+ ├── const.js # 常量定义(数据库文件名)
161
+ ├── dbInit.js # 数据库初始化与加载
162
+ ├── rm.js # 从数据库移除文件
163
+ ├── scan.js # 核心扫描逻辑
164
+ ├── stat.js # 文件系统统计信息收集
165
+ ├── upsert.js # 数据库持久化逻辑
166
+ └── test/ # 测试文件
212
167
  ```
213
168
 
214
- ## 6. 历史故事
215
-
216
- SQLite 的诞生源自导弹驱逐舰板载损害控制软件项目。2000 年,D. Richard Hipp 为美国海军设计该系统时,遭遇商业数据库因配置复杂、无法承受断连和崩溃之痛点。Hipp 随后设计出免服务器配置、直接读写本地文件之嵌入式数据库,即 SQLite。
217
-
218
- 为节省空间与降低读写延迟,SQLite 广泛应用了 Varint(可变字节整型)编码。在这种编码下,小整数仅占用 1 字节,只有大数值才占用更多字节。本项目在内存存储设计中对文件大小与修改时间采用同样的压缩设计,契合 SQLite 节省空间与高效之设计哲学。
169
+ ## 历史故事
219
170
 
171
+ 文件扫描工具源于早期Unix命令如`find`和`diff`。现代实现面临海量文件系统和云存储的新挑战。本实现借鉴了20世纪90年代开发的增量备份系统,该系统首创两阶段比对方法(先快速元数据检查,再按需内容验证),在速度与准确性间取得平衡。二进制数据结构的采用反映了当代针对内存受限环境和高性能计算场景的优化趋势。
220
172
  ## 关于
221
173
 
222
174
  本库由 [WebC.site](https://webc.site) 开发。
package/_.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { availableParallelism } from "node:os";
2
2
  import pLimit from "@3-/plimit";
3
3
  import dbInit from "./dbInit.js";
4
- import { mtime, md5 } from "./load.js";
5
4
  import scan from "./scan.js";
6
5
  import rm from "./rm.js";
7
6
  import upsert from "./upsert.js";
@@ -16,17 +15,17 @@ files: 待扫描的文件列表
16
15
  upsert: 用于将新扫描记录保存至数据库的 dispose 异步函数
17
16
  */
18
17
  export default async (dir, db_dir, files) => {
19
- const [db_mtime, db_md5] = dbInit(db_dir),
20
- existing_mtime = mtime(db_mtime),
21
- existing_md5 = md5(db_md5),
18
+ const [db_mtime, db_md5] = await dbInit(db_dir),
19
+ existing_mtime = db_mtime,
20
+ existing_md5 = db_md5,
22
21
  limit = pLimit(availableParallelism()),
23
22
  [scanned, update] = await scan(dir, files, existing_mtime, existing_md5, limit, db_mtime),
24
- rmPaths = (existing) => [...existing.keys()].filter((path) => !scanned.has(path));
23
+ rm_paths = (existing) => [...existing.keys()].filter((path) => !scanned.has(path));
25
24
 
26
25
  [
27
26
  [db_mtime, existing_mtime],
28
27
  [db_md5, existing_md5],
29
- ].forEach(([db, existing]) => rm(db, "scan", rmPaths(existing)));
28
+ ].forEach(([db, existing]) => rm(db, rm_paths(existing)));
30
29
 
31
- return [update, upsert(db_mtime, db_md5, dir)];
30
+ return [update, upsert(db_mtime, db_md5, dir, db_dir)];
32
31
  };
package/const.js ADDED
@@ -0,0 +1,2 @@
1
+ export const MTIME = "mtime",
2
+ MD5 = "md5";
package/dbInit.js CHANGED
@@ -1,16 +1,29 @@
1
- import sqlite from "@1-/sqlite";
1
+ import { BinMap } from "@3-/binmap";
2
+ import load from "@1-/csv/load.js";
2
3
  import upsertGitignore from "@1-/upsert_gitignore";
4
+ import vbE from "@3-/vb/vbE.js";
5
+ import b64Uint8 from "@3-/base64url/b64Uint8.js";
3
6
  import { existsSync } from "node:fs";
4
7
  import { join, basename } from "node:path";
8
+ import { MTIME, MD5 } from "./const.js";
9
+
10
+ const loadDb = async (path, db, parseVal) => {
11
+ if (existsSync(path)) {
12
+ const rows = await load(path);
13
+ rows.forEach(([path_str, ...vals]) => {
14
+ db.set(b64Uint8(path_str), parseVal(vals));
15
+ });
16
+ }
17
+ };
5
18
 
6
19
  /*
7
- 初始化/打开修改时间和 md5 的 sqlite 数据库,并将数据库文件加入 gitignore
20
+ 初始化/打开修改时间和 md5 的 csv 数据库,并将数据库文件加入 gitignore
8
21
  db_dir: 数据库存放目录
9
22
  返回值: [db_mtime, db_md5]
10
23
  */
11
- export default (db_dir) => {
12
- const li = ["mtime", "md5"],
13
- path_li = li.map((x) => join(db_dir, x + ".sqlite"));
24
+ export default async (db_dir) => {
25
+ const li = [MTIME, MD5],
26
+ path_li = li.map((x) => join(db_dir, x + ".csv"));
14
27
 
15
28
  if (path_li.some((x) => !existsSync(x))) {
16
29
  upsertGitignore(
@@ -19,12 +32,14 @@ export default (db_dir) => {
19
32
  );
20
33
  }
21
34
 
22
- const [db_mtime, db_md5] = path_li.map((x) => sqlite(x));
35
+ const db_mtime = new BinMap(),
36
+ db_md5 = new BinMap(),
37
+ [mtime_path, md5_path] = path_li;
23
38
 
24
- db_mtime.exec(
25
- "CREATE TABLE IF NOT EXISTS scan(path PRIMARY KEY,size INT UNSIGNED,mtime INT UNSIGNED)",
26
- );
27
- db_md5.exec("CREATE TABLE IF NOT EXISTS scan(path PRIMARY KEY,md5 BINARY(16))");
39
+ await Promise.all([
40
+ loadDb(mtime_path, db_mtime, ([size, mtime]) => vbE([Number(size), Number(mtime)])),
41
+ loadDb(md5_path, db_md5, ([md5_str]) => b64Uint8(md5_str)),
42
+ ]);
28
43
 
29
44
  return [db_mtime, db_md5];
30
45
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1-/scan",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Incrementally scan directory files and track metadata in SQLite / 增量扫描目录文件并使用 SQLite 记录元数据",
5
5
  "keywords": [
6
6
  "directory",
@@ -22,12 +22,13 @@
22
22
  "./*": "./*"
23
23
  },
24
24
  "dependencies": {
25
+ "@1-/csv": "^0.1.4",
25
26
  "@1-/hash": "^0.1.0",
26
27
  "@1-/md5": "^0.1.1",
27
- "@1-/sqlite": "^0.1.1",
28
- "@1-/upsert_gitignore": "^0.1.6",
29
- "@3-/binmap": "^0.1.21",
30
- "@3-/binset": "^0.1.7",
28
+ "@1-/upsert_gitignore": "^0.1.7",
29
+ "@3-/base64url": "^0.1.4",
30
+ "@3-/binmap": "^0.1.22",
31
+ "@3-/binset": "^0.1.8",
31
32
  "@3-/int": "^0.1.1",
32
33
  "@3-/plimit": "^0.1.3",
33
34
  "@3-/u8": "^0.1.2",
package/rm.js CHANGED
@@ -1,16 +1,8 @@
1
- import tx from "@1-/sqlite/tx.js";
2
-
3
1
  /*
4
2
  批量删除记录
5
- db: sqlite 实例
6
- table: 数据表名
3
+ db: BinMap 实例
7
4
  rm: 待删除的路径 path 数组
8
5
  */
9
- export default (db, table, rm) => {
10
- if (rm.length) {
11
- tx(db, () => {
12
- const del = db.prepare("DELETE FROM " + table + " WHERE path=?");
13
- rm.forEach((path) => del.run(path));
14
- });
15
- }
6
+ export default (db, rm) => {
7
+ rm.forEach((path) => db.delete(path));
16
8
  };
package/scan.js CHANGED
@@ -19,8 +19,7 @@ db_mtime: 修改时间数据库实例
19
19
  */
20
20
  export default async (dir, files, existing, existing_md5, limit, db_mtime) => {
21
21
  const scanned = new BinSet(),
22
- update = [],
23
- update_mtime = db_mtime.query("INSERT OR REPLACE INTO scan(path,size,mtime)VALUES(?,?,?)");
22
+ update = [];
24
23
 
25
24
  await Promise.all(
26
25
  files.map((rel_path) =>
@@ -38,7 +37,7 @@ export default async (dir, files, existing, existing_md5, limit, db_mtime) => {
38
37
  if (old_md5) {
39
38
  const cur_md5 = await pathMd5(join(dir, rel_path));
40
39
  if (u8eq(old_md5, cur_md5)) {
41
- update_mtime.run(path, size, mtime);
40
+ db_mtime.set(path, vbE([size, mtime]));
42
41
  return;
43
42
  }
44
43
  }
package/upsert.js CHANGED
@@ -1,28 +1,45 @@
1
+ import { writeFileSync } from "node:fs";
1
2
  import { join } from "node:path";
2
- import stat from "./stat.js";
3
+ import dumps from "@1-/csv/dumps.js";
4
+ import vbD from "@3-/vb/vbD.js";
5
+ import vbE from "@3-/vb/vbE.js";
6
+ import uint8B64 from "@3-/base64url/uint8B64.js";
3
7
  import pathMd5 from "@1-/md5/pathMd5.js";
8
+ import stat from "./stat.js";
9
+ import { MTIME, MD5 } from "./const.js";
10
+
11
+ const saveDb = (db_dir, db, name, toRow) => {
12
+ const li = [];
13
+ for (const [key, val] of db.entries()) {
14
+ li.push(toRow(key, val));
15
+ }
16
+ writeFileSync(join(db_dir, name + ".csv"), dumps(li), "utf8");
17
+ };
4
18
 
5
19
  /*
6
- 创建用于插入/更新文件元数据(大小、修改时间、md5)的函数,并在资源释放时关闭数据库
7
- db_mtime: 修改时间数据库实例
8
- db_md5: md5 数据库实例
20
+ 创建用于插入/更新文件元数据(大小、修改时间、md5)的函数,并在资源释放时同步写入 CSV 文件
21
+ db_mtime: 修改时间 BinMap 实例
22
+ db_md5: md5 BinMap 实例
9
23
  dir: 扫描目录
24
+ db_dir: 数据库(CSV)存放目录
10
25
  返回值: upsert 异步函数 (带有 [Symbol.dispose] 方法)
11
26
  */
12
- export default (db_mtime, db_md5, dir) => {
13
- const insert_mtime = db_mtime.query("INSERT OR REPLACE INTO scan(path,size,mtime)VALUES(?,?,?)"),
14
- insert_md5 = db_md5.query("INSERT OR REPLACE INTO scan(path,md5)VALUES(?,?)"),
15
- upsert = async (rel_path) => {
16
- try {
17
- const [size, mtime, path] = await stat(dir, rel_path),
18
- md5 = await pathMd5(join(dir, rel_path));
19
- insert_mtime.run(path, size, mtime);
20
- insert_md5.run(path, md5);
21
- } catch {}
22
- };
27
+ export default (db_mtime, db_md5, dir, db_dir) => {
28
+ const upsert = async (rel_path) => {
29
+ try {
30
+ const [size, mtime, path] = await stat(dir, rel_path),
31
+ md5 = await pathMd5(join(dir, rel_path));
32
+ db_mtime.set(path, vbE([size, mtime]));
33
+ db_md5.set(path, md5);
34
+ } catch {}
35
+ };
36
+
23
37
  upsert[Symbol.dispose] = () => {
24
- db_mtime.close();
25
- db_md5.close();
38
+ saveDb(db_dir, db_mtime, MTIME, (key, val) => [uint8B64(key), ...vbD(val)]);
39
+ saveDb(db_dir, db_md5, MD5, (key, val) => [uint8B64(key), uint8B64(val)]);
40
+ db_mtime[Symbol.dispose]();
41
+ db_md5[Symbol.dispose]();
26
42
  };
43
+
27
44
  return upsert;
28
45
  };
package/load.js DELETED
@@ -1,22 +0,0 @@
1
- import { BinMap } from "@3-/binmap";
2
- import vbE from "@3-/vb/vbE.js";
3
-
4
- /*
5
- 分别从修改时间数据库和 md5 数据库中加载记录,并创建内存 Map 缓存
6
- db: 数据库实例
7
- 返回值: 包含记录的 Map 缓存
8
- */
9
- export const mtime = (db) => {
10
- const existing = new BinMap();
11
- db.query("SELECT path,size,mtime FROM scan")
12
- .all()
13
- .forEach(({ path, size, mtime }) => existing.set(path, vbE([size, mtime])));
14
- return existing;
15
- },
16
- md5 = (db) => {
17
- const existing = new BinMap();
18
- db.query("SELECT path,md5 FROM scan")
19
- .all()
20
- .forEach(({ path, md5 }) => existing.set(path, md5));
21
- return existing;
22
- };