forked from weiran/wordpress-gatsby-migrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexporter.js
46 lines (39 loc) · 1.38 KB
/
exporter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const fs = require('fs-extra')
const fetch = require('node-fetch')
const templates = require('./templates.js')
const exportPosts = (posts, rootPath) => {
if (!rootPath.endsWith('/')) {
rootPath = rootPath + '/'
}
posts.forEach(async post => {
const postPath = `${__dirname}/${rootPath}${post.slug}`
await fs.ensureDir(postPath)
post.images.forEach(async image => {
try {
const imageResponse = await fetch(image.url)
const writeStream = fs.createWriteStream(`${postPath}/${image.fileName}`)
imageResponse.body.pipe(writeStream)
await streamAsync(writeStream)
} catch (error) {
console.error(error)
}
})
post.title = post.title.replace(/"/g, "\\\"") // escape quotes
const fileContents = templates.post(post.title, post.date.toISOString(), post.passthroughUrl, post.markdownContent)
await fs.outputFile(`${postPath}/index.md`, fileContents)
})
}
const streamAsync = (stream) => {
return new Promise((resolve, reject) => {
stream.on('end', () => {
resolve('end');
})
stream.on('finish', () => {
resolve('finish');
})
stream.on('error', (error) => {
reject(error);
})
})
}
module.exports = { exportPosts: exportPosts }