Skip to content

Instantly share code, notes, and snippets.

@isaacs
Last active April 27, 2021 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacs/3db535658c1cb0976126159d63286423 to your computer and use it in GitHub Desktop.
Save isaacs/3db535658c1cb0976126159d63286423 to your computer and use it in GitHub Desktop.
const walkUp = require('walk-up-path')
const { resolve } = require('path')
const { stat: stat_, statSync } = require('fs')
const { promisify } = require('util')
const stat = promisify(stat_)
function* binDirs (start, root) {
start = resolve(start)
root = resolve(root)
for (const path of walkUp(start)) {
yield resolve(path, 'node_modules/.bin')
if (path === root)
break
}
}
const fileExists = file => stat(file)
.then(st => st.isFile())
.catch(() => false)
const fileExistsSync = file => {
try {
return statSync(file).isFile()
} catch (e) {
return false
}
}
const findBin = async (bin, start, root) => {
for (const binDir of binDirs(start, root)) {
const path = resolve(binDir, bin)
if (await fileExists(path))
return path
}
return null
}
const findBinSync = (bin, start, root) => {
for (const binDir of binDirs(start, root)) {
const path = resolve(binDir, bin)
if (fileExists(path))
return path
}
return null
}
exports.binDirs = binDirs
exports.findBin = findBin
exports.findBinSync = findBinSync
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment