Skip to content

Instantly share code, notes, and snippets.

@GerardKetuma
Created September 30, 2021 20:20
Show Gist options
  • Save GerardKetuma/3c42cffb7f4745af7a0b517b5eed02db to your computer and use it in GitHub Desktop.
Save GerardKetuma/3c42cffb7f4745af7a0b517b5eed02db to your computer and use it in GitHub Desktop.
Node script to create a new post template for my blog.
#! /usr/bin/env node
const fs = require('fs');
const slugify = require('slug');
const inquirer = require('inquirer');
const open = require('open');
const pkgDir = require('pkg-dir');
inquirer.registerPrompt('datetime', require('inquirer-datepicker-prompt'));
(async () => {
try {
const rootDir = await pkgDir(__dirname);
const answers = await inquirer.prompt([
{
type: 'input',
name: 'title',
message: 'Title',
},
{
type: 'input',
name: 'slug',
default: (answers) => slugify(answers.title.toLowerCase()),
message: 'Slug',
},
{
type: 'checkbox',
name: 'category',
message: 'Select a category',
choices: [
{ name: 'AWS' },
{ name: 'CDK' },
{ name: 'TypeScript' },
{ name: 'React' },
{ name: 'DevOps' },
],
validate: (answer) =>
answer.length ? true : 'You must choose a category',
},
{
type: 'datetime',
name: 'date',
message: 'When would this post be published?',
format: [
'yyyy',
'-',
'mm',
'-',
'dd',
' ',
'hh',
':',
'MM',
':',
'ss',
' ',
'TT',
' ',
'Z',
],
validate: (answer) =>
answer.length ? true : 'You must enter a valid date and time',
},
{
type: 'datetime',
name: 'modified',
message: 'When was this post last modified?',
format: [
'yyyy',
'-',
'mm',
'-',
'dd',
' ',
'hh',
':',
'MM',
':',
'ss',
' ',
'TT',
' ',
'Z',
],
},
{
type: 'input',
name: 'thumbnail',
message: "Enter path to this post's thumbnail",
default: (answers) => `./images/${answers.slug}/${answers.slug}.png`,
},
{
type: 'input',
name: 'desc',
message: 'A short summary of the post: ',
},
{
type: 'confirm',
name: 'published',
default: false,
message: 'Publish?',
},
]);
const {
title,
slug,
category,
date,
modified,
thumbnail,
desc,
published,
} = answers;
const fileName = `${rootDir}/src/posts/blog/${slug}.md`;
if (fs.existsSync(fileName)) {
throw 'That post already exists!';
}
fs.writeFileSync(
fileName,
`---
title: '${title}'
category: '${category}'
date: '${date.toISOString()}'
modified: '${modified.toISOString()}'
thumbnail: '${thumbnail}'
desc: |
${desc}
published: ${published}
---
* <Start writing ...>
`
);
fs.mkdirSync(`${rootDir}/src/posts/blog/images/${slug}`, {
recursive: true,
});
// Wait for 1 second(s) to give Gatsby time to create page before we open it.
// Opening the pages immediately gives an error.
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log(`\n${slug} was created!`);
open(`http://localhost:8000/blog/${slug}`);
} catch (error) {
console.log({ error });
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment