The Node.js® Website
at main 2.0 kB view raw
1'use strict'; 2 3import { fileURLToPath } from 'node:url'; 4 5import { glob } from 'glob'; 6 7/** 8 * We create a locale cache of Glob Promises 9 * to avoid reading the file system multiple times 10 * this is done since we don't need to constantly re-run the glob 11 * query as it is only needed once 12 * 13 * @type {Map<string, Promise<string>>} */ 14const globCacheByPath = new Map(); 15 16export const getMatchingRoutes = (route = '', matches = []) => 17 matches.some(match => route === match); 18 19/** 20 * This method is responsible for reading all immediate subdirectories of a directory 21 * 22 * @param {string} root the root directory to search from 23 * @param {string} cwd the current working directory 24 * @returns {Promise<Array<string>>} a promise containing an array of directories 25 */ 26export const getDirectories = async (root, cwd) => { 27 return glob('*', { root, cwd, withFileTypes: true }) 28 .then(d => d.filter(e => e.isDirectory())) 29 .then(d => d.map(e => e.name)); 30}; 31 32/** 33 * This gets the relative path from `import.meta.url` 34 * 35 * @param {string} path the current import path 36 * @returns {string} the relative path from import 37 */ 38export const getRelativePath = path => fileURLToPath(new URL('.', path)); 39 40/** 41 * This method is responsible for retrieving a glob of all files that exist 42 * within a given language directory 43 * 44 * Note that we ignore the blog directory for static builds as otherwise generating 45 * that many pages would be too much for the build process to handle. 46 * 47 * @param {string} root the root directory to search from 48 * @param {string} cwd the given locale code 49 * @param {Array<string>} ignore an array of glob patterns to ignore 50 * @returns {Promise<Array<string>>} a promise containing an array of paths 51 */ 52export const getMarkdownFiles = async (root, cwd, ignore = []) => { 53 const cacheKey = `${root}${cwd}${ignore.join('')}`; 54 55 if (!globCacheByPath.has(cacheKey)) { 56 globCacheByPath.set(cacheKey, glob('**/*.{md,mdx}', { root, cwd, ignore })); 57 } 58 59 return globCacheByPath.get(cacheKey); 60};