1
0
Fork 0
blog/scripts/new.js

60 lines
1.6 KiB
JavaScript
Raw Normal View History

2018-11-01 19:35:18 +01:00
import fs from 'fs-extra'
2018-09-24 01:09:50 +02:00
import path from 'path'
import slugify from 'slugify'
import ora from 'ora'
const templatePath = path.join(__dirname, 'new.md')
2018-11-05 23:32:02 +01:00
const templatePathPhoto = path.join(__dirname, 'new-photo.md')
2018-09-24 01:09:50 +02:00
const template = fs.readFileSync(templatePath).toString()
2018-11-05 23:32:02 +01:00
const templatePhoto = fs.readFileSync(templatePathPhoto).toString()
2018-09-24 01:09:50 +02:00
2018-11-05 23:32:02 +01:00
const spinner = ora('Adding new post').start()
2018-09-24 01:09:50 +02:00
if (!process.argv[2]) {
2018-09-29 23:05:14 +02:00
spinner.fail('Use the format `npm run new "Title of post"`')
2018-09-24 01:09:50 +02:00
}
const title = process.argv[2]
2018-11-05 23:32:02 +01:00
const isPhoto = process.argv[3] === 'photo'
2018-09-24 01:09:50 +02:00
spinner.text = `Adding '${title}'.`
const titleSlug = slugify(title, { lower: true })
2018-09-29 23:05:14 +02:00
const postsPath = path.join('.', 'content', 'posts')
2018-11-05 23:32:02 +01:00
const photosPath = path.join('.', 'content', 'photos')
2018-09-29 23:05:14 +02:00
const date = new Date().toISOString()
2018-11-05 23:32:02 +01:00
const dateShort = date.slice(0, 10)
2018-09-24 01:09:50 +02:00
const newContents = template
.split('TITLE')
.join(title)
2018-11-05 23:32:02 +01:00
.split('SLUG')
2018-11-01 19:35:18 +01:00
.join(titleSlug)
2018-09-24 01:09:50 +02:00
.split('DATE')
2018-09-29 23:05:14 +02:00
.join(date)
2018-09-24 01:09:50 +02:00
2018-11-05 23:32:02 +01:00
const newContentsPhoto = templatePhoto
.split('TITLE')
.join(title)
.split('SLUG')
.join(titleSlug)
.split('DATE_LONG')
.join(date)
.split('DATE_SHORT')
.join(dateShort)
const file = `${postsPath}/${dateShort}-${titleSlug}/index.md`
const filePhoto = `${photosPath}/${dateShort}-${titleSlug}.md`
2018-09-29 23:05:14 +02:00
2018-11-05 23:32:02 +01:00
if (isPhoto) {
fs.appendFile(filePhoto, newContentsPhoto, err => {
if (err) spinner.fail(`Error creating photo post: ${err}`)
2018-11-01 19:35:18 +01:00
spinner.succeed(`New post '${title}' created.`)
})
2018-11-05 23:32:02 +01:00
} else {
fs.outputFile(file, newContents)
.then(() => fs.readFile(file, 'utf8'))
.then(() => spinner.succeed(`New post '${title}' created.`))
.catch(err => spinner.fail(`Error creating post: ${err}`))
}