blog/scripts/new-post.js

54 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-02-18 18:13:43 +08:00
/* This is a script to create a new post markdown file with front-matter */
import fs from "fs"
import path from "path"
function getDate() {
const today = new Date()
const year = today.getFullYear()
2024-02-18 18:13:43 +08:00
const month = String(today.getMonth() + 1).padStart(2, "0")
const day = String(today.getDate()).padStart(2, "0")
return `${year}-${month}-${day}`
}
const args = process.argv.slice(2)
if (args.length === 0) {
console.error(`Error: No filename argument provided
Usage: npm run new-post -- <filename>`)
process.exit(1) // Terminate the script and return error code 1
}
let fileName = args[0]
// Add .md extension if not present
const fileExtensionRegex = /\.(md|mdx)$/i
if (!fileExtensionRegex.test(fileName)) {
fileName += ".md"
}
const targetDir = "./src/content/posts/"
const fullPath = path.join(targetDir, fileName)
if (fs.existsSync(fullPath)) {
console.error(`ErrorFile ${fullPath} already exists `)
process.exit(1)
}
const content = `---
title: ${args[0]}
published: ${getDate()}
2024-01-21 20:19:34 +08:00
description: ''
image: ''
tags: []
2024-01-21 20:19:34 +08:00
category: ''
draft: false
language: ''
---
`
fs.writeFileSync(path.join(targetDir, fileName), content)
console.log(`Post ${fullPath} created`)