11const axios = require ( 'axios' ) ;
2+ const fs = require ( 'fs' ) ;
23const { join } = require ( 'path' ) ;
3- const fs = require ( 'fs' ) . promises ;
44
55const { PostsQuery, PostQuery } = require ( './query' ) ;
66
@@ -15,9 +15,11 @@ class Crawler {
1515 const posts = await this . getPosts ( ) ;
1616
1717 posts . map ( async ( postInfo , i ) => {
18- const post = await this . getPost ( postInfo . url_slug ) ;
18+ let post = await this . getPost ( postInfo . url_slug ) ;
1919
20+ post . body = await this . getImage ( post . body ) ;
2021 await this . writePost ( post ) ;
22+
2123 console . log ( `✅ " ${ post . title } " 백업 (${ i + 1 } /${ posts . length } )` ) ;
2224 } ) ;
2325
@@ -66,7 +68,7 @@ class Crawler {
6668 }
6769
6870 async writePost ( post ) {
69- const path = join ( './ backup' , `${ post . title } .md` ) ;
71+ const path = join ( 'backup' , 'content' , `${ post . title . replace ( / \/ / g , ' ' ) } .md` ) ;
7072
7173 post . body = '---\n'
7274 + `title: "${ post . title } "\n`
@@ -75,10 +77,27 @@ class Crawler {
7577 + `tags: ${ JSON . stringify ( post . tags ) } \n`
7678 + '---\n' + post . body ;
7779
78- await fs . writeFile ( path , post . body , 'utf8' ) ;
80+ await fs . promises . writeFile ( path , post . body , 'utf8' ) ;
7981 }
8082
83+ async getImage ( body ) {
84+ const regex = / ! \[ [ ^ \] ] * \] \( (?< filename > .* ?) (? = \" | \) ) (?< optionalpart > \" .* \" ) ? \) / g;
85+
86+ body = body . replace ( regex , ( _ , url ) => {
87+ const filename = url . replace ( / \/ \s * $ / , '' ) . split ( '/' ) . slice ( - 2 ) . join ( '-' ) ;
88+ const path = join ( 'backup' , 'images' , filename ) ;
89+
90+ axios ( {
91+ method : 'get' ,
92+ url,
93+ responseType : 'stream'
94+ } ) . then ( resp => resp . data . pipe ( fs . createWriteStream ( path ) ) ) ;
8195
96+ return `` ;
97+ } ) ;
98+
99+ return body ;
100+ }
82101} ;
83102
84103module . exports = Crawler ;
0 commit comments