Next.js "New Post" Node Script
This file contains 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 slugify = require("slug"); | |
const inquirer = require("inquirer"); | |
const open = require("open"); | |
// Register datepicker plugin for inquirer | |
inquirer.registerPrompt("datetime", require("inquirer-datepicker-prompt")); | |
inquirer | |
.prompt([ | |
{ | |
type: "input", | |
name: "title", | |
message: "Title" | |
}, | |
{ | |
type: "input", | |
name: "slug", | |
default: answers => slugify(answers.title.toLowerCase()), | |
message: "Slug" | |
}, | |
{ | |
type: "input", | |
name: "desc", | |
message: "Description" | |
}, | |
{ | |
type: "confirm", | |
name: "draft", | |
default: true, | |
message: "Is Draft?" | |
}, | |
{ | |
type: "confirm", | |
name: "published", | |
default: false, | |
message: "Is Published?" | |
}, | |
{ | |
type: "checkbox", | |
message: "Select categories", | |
name: "categories", | |
choices: [ | |
{ name: "JavaScript" }, | |
{ name: "React" }, | |
{ name: "CSS" }, | |
{ name: "Comic" }, | |
{ name: "Neovim" }, | |
{ name: "Vim" }, | |
{ name: "Command Line" } | |
], | |
validate: answer => | |
answer.length ? true : "You must choose at least one category" | |
}, | |
{ | |
type: "datetime", | |
name: "date", | |
message: "When would you like the post to be published?", | |
format: ["yyyy", "/", "mm", "/", "dd"] | |
} | |
]) | |
.then(answers => { | |
const { slug, date, title, desc, categories, draft, published } = answers; | |
date.setHours(12, 0, 0, 0); | |
const fileName = `/posts/${slug}.mdx`; | |
if (fs.existsSync(fileName)) { | |
throw "That post already exists!"; | |
} | |
fs.writeFileSync( | |
`posts/${ slug }.mdx`, | |
`--- | |
slug: "${slug}" | |
date: "${date.toISOString()}" | |
title: "${title}" | |
description: "${desc}" | |
categories: ${JSON.stringify(categories)} | |
draft: ${draft} | |
published: ${published} | |
--- | |
## Introduction | |
`); | |
fs.mkdirSync(`public/images/${slug}`, { recursive: true }); | |
console.log(`\n${slug} was created!`); | |
open(`http://localhost:3000/blog/${slug}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment