Skip to content

Commit 3cd8c29

Browse files
committed
Fix Error & Add Image downloader
1 parent fe09f36 commit 3cd8c29

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

app.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ const Crawler = require('./crawler');
33

44
const program = new Command();
55

6-
program.version('0.0.1');
6+
program.version('1.0.0');
77
program.option('-u, --username <username>', 'velog 유저이름');
88

99
program.parse(process.argv);
1010

1111
const crawler = new Crawler(program.username);
1212

13-
console.log(JSON.stringify(crawler.parse()));
13+
JSON.stringify(crawler.parse());

crawler/index.js

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const axios = require('axios');
2+
const fs = require('fs');
23
const { join } = require('path');
3-
const fs = require('fs').promises;
44

55
const { 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 `![](/images/${filename})`;
97+
});
98+
99+
return body;
100+
}
82101
};
83102

84103
module.exports = Crawler;

0 commit comments

Comments
 (0)