Created
March 9, 2017 20:42
-
-
Save spasiu/0d002e00fa8b5f0890fce832e1fb2c48 to your computer and use it in GitHub Desktop.
Script to split Markdown files
This file contains hidden or 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 fs = require('fs'); | |
| const PATH = process.argv[2] || __dirname; | |
| const LEVEL = parseInt(process.argv[3] || 1); | |
| const TARGET = process.argv[4]; | |
| const DELETE = process.argv[5]; | |
| fs.readdirSync(PATH) | |
| .filter(isOptionalTarget) | |
| .filter(isMarkdownFile) | |
| .map(readFile) | |
| .map(splitContent) | |
| .map(doCreateFolders) | |
| .map(doCreateFiles) | |
| .map(doOptionalCleanupFiles) | |
| .map(log); | |
| function readFile(filename) { | |
| const content = fs.readFileSync(`${PATH}/${filename}`).toString(); | |
| const dirname = filename.replace(/^_/, '').replace('.md', ''); | |
| return { filename, dirname, content }; | |
| } | |
| function splitContent(data) { | |
| const re = RegExp(`\n\n(#{${LEVEL}} .*\n)`, 'g'); | |
| const markup = data.content.replace(re, match => { | |
| return '-->slice<--' + match.trim(); | |
| }); | |
| const sections = markup.split('-->slice<--') | |
| .map(text => text.trim()) | |
| .map(text => ({ | |
| title: text | |
| .slice(0, text.indexOf('\n')) | |
| .replace(/#+\s/, '') | |
| .replace(/\s/g, '_') | |
| .toLowerCase(), | |
| text | |
| })); | |
| return Object.assign(data, { sections }); | |
| } | |
| fucntion isOptionalTarget(filename) { | |
| return !TARGET || filename === TARGET; | |
| } | |
| function isMarkdownFile(filename) { | |
| return /\.md$/.test(filename); | |
| } | |
| function doCreateFolders(data) { | |
| fs.mkdirSync(`${PATH}/${data.dirname}`); | |
| return data; | |
| } | |
| function doCreateFiles(data) { | |
| data.sections.forEach(section => { | |
| const title = `_${section.title}.md`; | |
| fs.writeFileSync(`${PATH}/${data.dirname}/${title}`, section.text); | |
| }); | |
| return data; | |
| } | |
| function doOptionalCleanupFiles(data) { | |
| if (DELETE) { | |
| fs.unlinkSync(`${PATH}/${data.filename}`); | |
| } | |
| return data; | |
| } | |
| function log(data) { | |
| console.log(data.dirname); | |
| data.sections.forEach(section => { | |
| console.log(data.dirname + '/' + section.title); | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment