guidebook/src/lib/pages.js

71 lines
1.8 KiB
JavaScript

import * as fs from 'fs/promises';
import { resolve } from 'path';
import timeToRead from 'time-to-read';
import { exists } from './fs';
export const storageDir = resolve('storage/');
/**
* @param {string} name
*/
export async function getPost(name, chars) {
try {
let path = `${storageDir}/${name}`;
let meta = JSON.parse(await fs.readFile(`${path}.json`, 'utf8'));
let data = await fs.readFile(`${path}.md`, 'utf8');
return {
...meta,
path: name,
content: chars ? data.slice(0, chars) : data,
truncated: chars && data.length > chars,
size: data.length,
timeToRead: timeToRead(data)
};
} catch(err) {
// probably a 404
console.log(err);
return;
}
}
async function scanDir(dir) {
let posts = [];
for (const file of await fs.readdir(dir)) {
let path = resolve(dir, file);
if (file.endsWith('.json')) {
posts.push(await getPost(path.replace(storageDir + '/', '').slice(0, -5), 256));
} else if ((await fs.stat(path)).isDirectory()) {
posts.push(...await scanDir(path));
}
}
return posts;
}
export async function getPosts(dir) {
return scanDir(storageDir + (dir || ''));
}
export async function getPostsFlat(dir) {
let posts = [];
let postsDir = resolve(storageDir, dir);
for (const file of await fs.readdir(postsDir)) {
let path = resolve(postsDir, file);
if (file.endsWith('.json')) {
let name = path.replace(storageDir + '/', '').slice(0, -5);
posts.push(await getPost(name, 256));
}
}
return posts;
}
export async function isDir(dir) {
let path = resolve(storageDir, dir);
let statDir = await exists(path);
if (statDir && statDir.isDirectory()) {
return true;
} else {
let statFile = await exists(path + '.json');
if (statFile) return false;
return null;
}
}