1+ import fs from 'fs-extra'
2+ import path from 'path'
3+ import imageSize from 'image-size'
4+ import { promisify } from 'util'
5+ import type { WImage } from './traverseFolder'
6+ import { mainWindow } from './electron-main'
7+
8+ const sizeOf = promisify ( imageSize )
9+
10+ export default class AsyncReadFilePath {
11+ picLinks = [ ] as WImage [ ]
12+ /** 有效的图片格式 */
13+ picFormats = [ ] as string [ ]
14+ /** 任务名称 */
15+ taskName
16+ /** 每页分割的大小 */
17+ pageSize = 20
18+
19+ constructor ( taskName : string , picFormats : string [ ] , pageSize : number ) {
20+ this . taskName = taskName
21+ this . picFormats = picFormats
22+ this . pageSize = pageSize || 20
23+ }
24+
25+ async readDirectory ( dir : string ) {
26+ const stack = [ dir ]
27+ const pageStack = [ ] as WImage [ ]
28+
29+ while ( stack . length ) {
30+ // 深度优先
31+ const currentPath = stack . pop ( )
32+ if ( ! currentPath ) {
33+ continue
34+ }
35+ const files = await fs . readdir ( currentPath , { withFileTypes : true } )
36+ files . sort ( ( a , b ) => b . name . localeCompare ( a . name , undefined , { sensitivity : 'base' } ) )
37+
38+ const result = [ ] as WImage [ ]
39+ for ( const file of files ) {
40+ const fullPath = path . join ( currentPath , file . name )
41+ if ( file . isDirectory ( ) ) {
42+ stack . push ( fullPath )
43+ } else if ( file . isFile ( ) ) {
44+ const extname = path . extname ( fullPath ) . toLowerCase ( )
45+ if ( this . picFormats . includes ( extname ) ) {
46+ await sizeOf ( fullPath ) . then ( dimensions => {
47+ result . push ( {
48+ source : fullPath ,
49+ src : 'atom://' + fullPath ,
50+ srcThumb : 'atom://' + fullPath ,
51+ width : dimensions ?. width ,
52+ height : dimensions ?. height ,
53+ } )
54+
55+ } ) . catch ( err => {
56+ console . log ( 'sizeOf error' , err )
57+ } )
58+ }
59+ }
60+ }
61+ pageStack . push ( ...result . reverse ( ) )
62+ if ( pageStack . length >= this . pageSize ) {
63+ this . picLinks . push ( ...pageStack . splice ( 0 , this . pageSize ) )
64+ this . taskReport ( )
65+ }
66+ }
67+
68+ if ( pageStack . length ) {
69+ this . picLinks . push ( ...pageStack . splice ( 0 , pageStack . length - 1 ) )
70+ this . taskReport ( )
71+ }
72+
73+ }
74+
75+ taskReport ( ) {
76+ if ( mainWindow && this . picLinks . length ) {
77+ mainWindow . webContents . send ( 'async:imageLinks-append' , this . taskName , this . picLinks )
78+ }
79+ }
80+ }
0 commit comments