Skip to content

Instantly share code, notes, and snippets.

@isaacs

isaacs/index.js

Last active Apr 27, 2021
Embed
What would you like to do?
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