1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-11-22 09:56:51 +01:00
blog/scripts/new/createArticlePost.ts
Matthias Kretschmann 05ad0470c2
migrate to biome (#944)
* migrate to biome

* cleanup

* fix

* use tsx

* script tweaks

* fix test runs

* path tweaks
2024-07-27 21:15:05 +01:00

53 lines
1.4 KiB
TypeScript

import { existsSync, mkdirSync, readFileSync } from 'node:fs'
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Ora } from 'ora'
import { slugify } from '../../src/lib/slugify/slugify.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const templatePath = path.join(__dirname, 'new-article.md')
export async function createArticlePost(
dest: string,
spinner: Ora,
title: string,
newDate?: string
) {
let file = ''
const date = newDate
? new Date(newDate).toISOString()
: new Date().toISOString()
spinner.text = `Adding '${title}'.`
try {
const titleSlug = slugify(title)
const dateShort = date.slice(0, 10)
const folderName = `${dateShort}-${titleSlug}`
const destination = `${dest}/${folderName}`
file = `${destination}/index.md`
const template = readFileSync(templatePath).toString()
const newContents = template
.split('TITLE')
.join(title)
.split('SLUG')
.join(titleSlug)
.split('DATE')
.join(date)
// Create the destination folder if it doesn't exist
if (!existsSync(destination)) {
mkdirSync(destination, { recursive: true })
}
// create post file
await fs.appendFile(file, newContents)
spinner.succeed(`New post '${title}' created.`)
} catch (error: unknown) {
spinner.fail((error as Error).message)
}
return file
}