UNPKG

2.71 kBJavaScriptView Raw
1const fs = require('fs');
2const md = require('./markdown-settings');
3const mdx = /(\.md$|\.markdown$)/
4const template = require('./document-template');
5
6function grayson(options){
7 try {
8 let directory = fs.readdirSync(options.input).filter(file => file.match(mdx));
9 let navigation = ['/'].concat(directory
10 .filter(filename => !filename.match(/index/))
11 .map(filename => `/${filename.replace(/(md$|markdown$)/, 'html')}`));
12 let result = directory
13 .map(source => {
14 source = fs.readFileSync(options.input + '/' + source).toString();
15 return options.slides ? `:::slide\n${source}\n:::` : source;
16 });
17
18 if(options.output){
19 switch(options.mode){
20 case 'slides':
21 fs.writeFileSync(`${options.output.replace(/\/$/, '')}/slides.html`, template({
22 content: {
23 id: '',
24 nav: null,
25 body: md.render(result.join(''))
26 },
27 metadata: options.metadata
28 }));
29 break;
30 case 'blog':
31 fs.writeFileSync(`${options.output}/index.html`, template({
32 content: {
33 id: 'index',
34 nav: navigation,
35 body: ''
36 },
37 metadata: options.metadata
38 }))
39 default:
40 directory.forEach((file, i) => {
41 let input = `${options.input.replace(/\/$/, '')}/${file}`;
42 writeFile(Object.assign({}, options, {
43 input,
44 html: template({
45 content: {
46 id: file.replace(/\.(md$|markdown$)/, ''),
47 body: md.render(result[i]),
48 nav: navigation
49 },
50 metadata: options.metadata
51 })
52 }));
53 });
54 break;
55 }
56 }
57
58 return result;
59 } catch (err) {
60 if(err.message.match(/not a directory/ig) && options.input.match(mdx)){
61 if(options.output){
62 return writeFile(Object.assign({}, options, {
63 html: template({
64 content: {
65 id: options.input.slice(options.input.lastIndexOf('/')).replace(/(md$|markdown$)/, ''),
66 body: md.render(fs.readFileSync(options.input).toString()),
67 nav: null
68 },
69 metadata: options.metadata
70 })
71 }));
72 }
73
74 return template({
75 content: {
76 id: options.input.slice(options.input.lastIndexOf('/')).replace(/(md$|markdown$)/, ''),
77 body: md.render(fs.readFileSync(options.input).toString()),
78 nav: null
79 },
80 metadata: options.metadata
81 });
82 }
83
84 throw err;
85 }
86}
87
88function writeFile(options){
89 if(!options.output || !fs.existsSync(options.output)){
90 throw new Error('Invalid output directory');
91 }
92
93 let source = options.input.slice(options.input.lastIndexOf('/'));
94 let filename = `${options.output.replace(/\/$/, '')}/${source.replace(/(md$|markdown$)/, 'html')}`;
95
96 return fs.writeFileSync(filename, options.html);
97}
98
99module.exports = grayson;