I store the primary versions of all my posts locally as versioned markdown files, that I past into Ghost when I’m ready to publish. The Ghost editor has gotten so nice, I often want to use it for drafting posts. However, there’s no way to copy-and-paste the formatting out of the editor into a Markdown file.
I looked around and couldn’t find any existing scripts to get post markdown by ID, so I wrote a little script to fetch the content of a post by ID, and then convert it with Pandoc, and thought I’d share it in case it’s useful for other people:
// First:
// npm install @tryghost/admin-api
// Run with:
// node get-post-as-markdown.js "POSTID" https://blah.ghost.io "ADMIN_API_KEY" | pandoc -f html+smart -t markdown-smart
if (process.argv.length < 4) {
console.error('Missing an argument');
process.exit(1);
}
const postId = process.argv[2];
const url = process.argv[3];
const key = process.argv[4];
const GhostAdminAPI = require('@tryghost/admin-api');
const api = new GhostAdminAPI({
url: url,
key: key,
version: 'v6.8'
});
api.posts.read({id: postId}, {formats: ['html']})
.then((post) => {
console.log("<h1>"+post.title+"</h1>")
console.log("<h2>"+post.excerpt+"</h2>")
console.log(""+post.slug+"")
console.log(post.html);
})
.catch((err) => {
console.error(err);
});
Run it with:
node get-post-as-markdown.js "POSTID" https://blah.ghost.io "ADMIN_API_KEY" | pandoc -f html+smart -t markdown-smart --wrap="preserve"
or
node get-post-as-markdown.js "POSTID" https://blah.ghost.io "ADMIN_API_KEY" | pandoc -f html+smart -t markdown-smart --wrap="preserve" -o "My Output Filename.md"