Skip to content

Instantly share code, notes, and snippets.

@MadeByMike
Created November 15, 2019 01:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadeByMike/36678f27fbec3cbc1c5dcb2183c776fc to your computer and use it in GitHub Desktop.
Save MadeByMike/36678f27fbec3cbc1c5dcb2183c776fc to your computer and use it in GitHub Desktop.
// Convert contentful CLI export to markdown with node
const slugify = require('slugify')
const fs = require('fs')
const data = require('./data.json')
const sanatiseFields = fields => {
return Object.keys(fields).reduce((prev, next) => {
prev[next] = fields[next]['en-US'] ? fields[next]['en-US'] : fields[next]
return prev
}, {})
}
const { entries } = data
entries
.forEach(entry => {
const {
title,
pageTitle,
slug,
description,
body,
publishDate,
tags,
} = sanatiseFields(entry.fields)
const frontMatterThis = fields => {
const f = d => {
if (d === 'true' || d === true) return 'true'
if (d === 'false' || d === false) return 'false'
return JSON.stringify(d)
}
if (!fields) return
let frontMatter = '---\n'
Object.keys(fields).forEach(key => {
const data = fields[key]
if (typeof data === 'string') {
frontMatter += `${key}: ${f(data)}\n`
}
if (Array.isArray(data)) {
frontMatter += `${key}:\n`
data.forEach(item => {
frontMatter += ` - ${f(item)}\n` // Going to assume string at this point
})
}
})
frontMatter += '---\n'
return frontMatter
}
const content = `
${frontMatterThis({
title,
pageTitle,
slug,
description,
publishDate,
tags,
})}
${body || ''}
`
try {
fs.writeFileSync(`${slug || slugify(title)}.md`, content)
} catch (e) {
console.log('Cannot write file, :( Oh, the saddness!', e)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment