Skip to content

Commit 117d45b

Browse files
committed
Refactoring using mapping for downloading files
1 parent d35d513 commit 117d45b

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

src/downloadFiles.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ const tasks = ($, links, url, filesDirPath, selector, attr) => new Listr(links
1616
task: () => downloadFile($, link, absLink, filesDirPath, selector, attr),
1717
}
1818
}
19-
else return null
19+
return null
2020
})
21-
.filter(link => link !== null && link !== undefined), {
21+
.filter(Boolean), {
2222
concurrent: true,
2323
exitOnError: false,
2424
})
@@ -48,9 +48,7 @@ const downloadFile = ($, link, absLink, filesDirPath, selector, attr) => {
4848
})
4949
}
5050

51-
const downloadFiles = ($, url, filesDirPath, selector, attr) => {
52-
const links = $(selector).map((i, tag) => $(tag).attr(attr)).get()
53-
51+
const downloadFiles = ($, url, filesDirPath, selector, attr, links) => {
5452
if (links.length === 0) {
5553
log('no %s links', selector)
5654
return Promise.resolve()

src/index.js

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ const log = debug('page-loader')
1010

1111
const getAbsolutePath = dirpath => path.resolve(process.cwd(), dirpath)
1212

13+
const attributeMapping = {
14+
img: 'src',
15+
link: 'href',
16+
script: 'src',
17+
}
18+
1319
const downloadPage = (url, outputDir = process.cwd()) => {
1420
log('download page %s to %s', url, outputDir)
1521

@@ -28,11 +34,14 @@ const downloadPage = (url, outputDir = process.cwd()) => {
2834
log('HTML downloaded')
2935
const $ = cheerio.load(html)
3036

31-
return Promise.all([
32-
downloadFiles($, url, filesDirPath, 'img', 'src'),
33-
downloadFiles($, url, filesDirPath, 'link', 'href'),
34-
downloadFiles($, url, filesDirPath, 'script', 'src'),
35-
])
37+
return Promise.all(
38+
Object.entries(attributeMapping).map(([tag, attr]) => {
39+
const $elements = $(tag).toArray()
40+
const elementsWithUrls = $elements
41+
.map(el => $(el).attr(attr))
42+
.filter(Boolean)
43+
return downloadFiles($, url, filesDirPath, tag, attr, elementsWithUrls)
44+
}))
3645
.then(() => $)
3746
})
3847
.then(($) => {

0 commit comments

Comments
 (0)