Skip to content

Instantly share code, notes, and snippets.

@ramsaylanier
Last active January 14, 2019 17:56
Show Gist options
  • Save ramsaylanier/b23e9435f65cc4bd880292a2788b226d to your computer and use it in GitHub Desktop.
Save ramsaylanier/b23e9435f65cc4bd880292a2788b226d to your computer and use it in GitHub Desktop.
Module Docs fileController
const fs = require("fs")
const pipe = require("lodash/fp/pipe")
const some = require("lodash/some")
const promisify = require("util").promisify
const readdir = promisify(fs.readdir)
const readFile = promisify(fs.readFile)
// directories to exclude from the search
const blacklist = [".bin", ".cache", ".yarn-integrity"]
const filterThroughBlacklist = files =>
files.filter(f => !blacklist.includes(f))
// check to see if the list of files includes the filename
const checkFilesForFile = files => fileName =>
some(files, f => f.name === fileName)
// Get all the files in the package that are directories. This is used
// for mono-repos are scoped packages that don't contain README files directly.
// I could probably refactor this and the blackListFilter into one util function
const getDirectories = files =>
files.filter(f => f.isDirectory() && f.name !== "node_modules")
// checks a package directory to see if it contains a README or a package.json file
const checkPackage = files => {
const checkFilesFor = checkFilesForFile(files)
return {
hasReadme: checkFilesFor("README.md"),
hasPackageInfo: checkFilesFor("package.json")
}
}
// gets the content of the README and the package.json file, if they exist
const getDirectoryContent = async directory => {
const files = await readdir(directory, { withFileTypes: true })
const { hasReadme, hasPackageInfo } = checkPackage(files)
const readmeContent =
hasReadme && (await readFile(`${directory}/README.md`, "utf8"))
const packageInfo =
hasPackageInfo && (await readFile(`${directory}/package.json`, "utf8"))
return {
files,
readmeContent,
packageInfo
}
}
// If a package has sub-directories, check each directory for a README and package.json
// If they exists, get contents of each and return
const getPackagesFromChildren = parentDir => children => {
const readmes = children.map(async child => {
const childDir = `${parentDir}/${child.name}`
const { readmeContent, packageInfo } = await getDirectoryContent(childDir)
return readmeContent || packageInfo
? {
name: child.name,
path: `${childDir}/README.md`,
content: readmeContent,
info: packageInfo
}
: {}
})
return Promise.all(readmes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment