/
utils.ts
38 lines (33 loc) · 958 Bytes
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import fs from 'fs';
import path from 'path'
export function getLocaleFromFilename(name: string): string | void {
const localeRegex = /\.([a-zA-Z-]+)?\.(mdx?|jsx?|json)$/
const match = name.match(localeRegex)
if (match) return match[1]
}
export function removeExtension(name: string): string {
const match = name.match(/^([^.]+)/)
return match !== null ? match[1] : ''
}
export function getFileName(resourcePath: string): string {
return removeExtension(path.basename(resourcePath))
}
export const parseJsonFile: (
content: string,
path: string
) => Record<string, any> = (content: string, path: string) => {
try {
return JSON.parse(content)
} catch (err) {
console.error(`[nextra] Error parsing ${path}, make sure it's a valid JSON`, err)
return {}
}
}
export const existsSync = (filePath: string): boolean => {
try {
fs.accessSync(filePath, fs.constants.F_OK)
return true
} catch {
return false
}
}