Skip to content

Instantly share code, notes, and snippets.

@joshuawootonn
Last active May 16, 2022 22:43
Show Gist options
  • Save joshuawootonn/8e2646d94a67177c9de2ef681fd8c724 to your computer and use it in GitHub Desktop.
Save joshuawootonn/8e2646d94a67177c9de2ef681fd8c724 to your computer and use it in GitHub Desktop.
Export notion table to markdown with greymatter
const fs = require('fs-extra');
const { Client } = require('@notionhq/client');
const notion2md = require('notion-to-md');
const { promisify } = require('util');
const removeAsync = promisify(fs.remove);
const writeFileAsync = promisify(fs.writeFile);
const mkdirAsync = promisify(fs.mkdir);
const existsAsync = promisify(fs.exists);
const notion = new Client({ auth: process.env.NOTION_TOKEN });
const n2m = new notion2md({ notionClient: notion });
const getRichText = prop =>
prop.rich_text.reduce((acc, curr) => acc + curr.plain_text, '');
const createMarkdownFromPage = async page => {
const mdblocks = await n2m.pageToMarkdown(page.id);
const md = n2m.toMarkdownString(mdblocks);
const content = {
md,
title: getRichText(page.properties['Title']),
seoTitle: getRichText(page.properties['Seo Title']),
description: getRichText(page.properties['Description']),
seoDescription: getRichText(page.properties['Seo Description']),
publishedOn: page.properties['Date Published'].date.start,
};
console.log(`Title: ${content.title}`);
const cleanTitle = content.title.replace(/[^a-z0-9]/gi, '-').toLowerCase();
const potentialDirectory = `./public/content/${cleanTitle}`;
console.log(`Using Directory: ${potentialDirectory}`);
const isDirectoryAlreadyCreated = await existsAsync(potentialDirectory);
if (isDirectoryAlreadyCreated) {
await removeAsync(potentialDirectory);
}
await mkdirAsync(potentialDirectory);
const error = await writeFileAsync(
`${potentialDirectory}/index.mdx`,
`---
title: ${content.title}
seoTitle: ${content.seoTitle}
abstract: ${content.description}
description: ${content.seoDescription}
publishedOn: ${content.publishedOn}T06:00:00-0400
template: Thought
---
` + content.md
);
};
(async () => {
try {
// https://www.notion.so/4c2d0c5d635b47b99f1984c454cf1f92?v=6d1a70da2ebb46f38c16e2a3d0e08623
const response = await notion.databases.query({
database_id: '4c2d0c5d635b47b99f1984c454cf1f92',
filter: {
property: 'Status',
['multi_select']: {
contains: 'Published',
},
},
sorts: [
{
property: 'Date Published',
direction: 'ascending',
},
],
});
await Promise.all(
response.results.map(page => createMarkdownFromPage(page))
);
console.log(`
Completed ${response.results.length} thoughts!`);
} catch (e) {
console.log(
`
Failed with error!`,
e
);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment