-
Notifications
You must be signed in to change notification settings - Fork 0
/
generatePost.js
93 lines (77 loc) · 2.33 KB
/
generatePost.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import dedent from "dedent";
import fs from 'fs'
import prompts from 'prompts'
const questions = [
{
name: 'title',
message: 'Enter post title : ',
validate: name => name.length < 5 ? `Invalid Length` : true,
type: 'text',
},
{
name: 'author',
message: 'Enter author name : ',
initial: 'Tuantq',
type: 'text',
},
{
name: 'tags',
message: 'Enter your tags : ',
type: 'text',
},
{
name: 'teaser',
message: 'Enter teaser :',
type: 'text',
},
];
const formatDate = () => {
let d = new Date()
return [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2),
].join('-')
}
const capitalizeFLetter = (title) => {
return title[0].toUpperCase() + title.slice(1)
}
const skeletonContents = (answers) => {
const tagArray = answers.tags.split(',')
tagArray.forEach((tag, index) => (tagArray[index] = tag.trim()))
const tags = "'" + tagArray.join("','") + "'"
let contents = dedent`---
title: ${answers.title ? capitalizeFLetter(answers.title) : 'Untitled Blog'}
author: ${answers.author ? answers.author : ''}
tags: [${answers.tags ? tags : ''}]
teaser: ${answers.teaser ? answers.teaser : ' '}
`
contents += '\n---' + '\nContent go here !'
return contents
}
const makeFileName = (title) => {
let fileName = title
.toLowerCase()
.replace(/[^a-zA-Z0-9 ]/g, '')
.replace(/ /g, '-')
.replace(/-+/g, '-')
return formatDate() + '.' + fileName
}
const makeFilePath = (title) => {
const fileName = makeFileName(title)
if (!fs.existsSync('./storage/app/posts')) fs.mkdirSync('storage/app/posts', { recursive: true })
return `./storage/app/posts/${fileName ? fileName : 'untitled'}.md`
}
(async () => {
const answers = await prompts(questions);
// answers => { title, author, tags, teaser }
const contents = skeletonContents(answers)
const filePath = makeFilePath(answers.title)
fs.writeFile(filePath, contents, { flag: 'wx' }, (err) => {
if (err) {
throw err
} else {
console.log(`\nBlog post generated successfully at ${filePath}`)
}
})
})();