Last active
May 8, 2021 18:41
-
-
Save fuergaosi233/a0e5562453077ee10eb33d4dde74d766 to your computer and use it in GitHub Desktop.
Migrate from hexo to ghost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require("axios"); | |
const jsyaml = require("js-yaml"); | |
const promisify = require("util").promisify; | |
const fs = require("fs"); | |
const fsPromises = fs.promises; | |
const ProgressBar = require("progress"); | |
const GHOST_HOST = process.GHOST_HOST; | |
const ADMIN_API_KEY = process.ADMIN_API_KEY; | |
const path = require("path"); | |
// The admin API client is the easiest way to use the API | |
const GhostAdminAPI = require("@tryghost/admin-api"); | |
// Configure the client | |
const api = new GhostAdminAPI({ | |
url: GHOST_HOST, | |
// Admin API key goes here | |
key: ADMIN_API_KEY, | |
version: "v3", | |
}); | |
function genPost({ title, createTime, tags, body, slug }) { | |
let mobiledoc = { | |
version: "0.3.1", | |
atoms: [], | |
cards: [["markdown", { markdown: body }]], | |
markups: [], | |
sections: [ | |
[10, 0], | |
[1, "p", []], | |
], | |
}; | |
return { | |
title, | |
status: "published", | |
tags: tags.map((tag) => { | |
return { | |
name: tag, | |
}; | |
}), | |
mobiledoc: JSON.stringify(mobiledoc), | |
published_at: createTime, | |
created_at: createTime, | |
updated_at: createTime, | |
}; | |
} | |
async function main(filePath = process.cwd()) { | |
postsDirPath = path.join(filePath, "_posts"); | |
let fileNames = await fsPromises.readdir(postsDirPath); | |
fileNames = fileNames.filter((fileName) => { | |
return /md$/.test(fileName); | |
}); | |
let count = fileNames.length; | |
var bar = new ProgressBar(":bar", { total: count }); | |
let postsPromises =await Promise.all( | |
fileNames.map(async (fileName) => { | |
let filePath = path.join(postsDirPath, fileName); | |
let body = await fsPromises.readFile(filePath, { encoding: "utf-8" }); | |
let [metaData] = /---([\s\S]*?)---/.exec(body); | |
metaData = jsyaml.load(metaData.replace(/---/g, "")); | |
console.log(metaData) | |
body = body.replace(/---([\s\S]*?)---/g, ""); | |
let res = await api.posts.add( | |
genPost({ | |
title: metaData.title, | |
body, | |
createTime: metaData.date, | |
tags: metaData.tags||[], | |
slug: fileName, | |
}) | |
); | |
bar.tick(); | |
}) | |
); | |
return "ok" | |
} | |
main().then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment