Created
March 27, 2018 12:16
-
-
Save emmiep/775037095be001ddc123243a7990cf1a to your computer and use it in GitHub Desktop.
Node lookup executable in $PATH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const FS = require('fs'); | |
const Path = require('path'); | |
function getExecutablePath(name) { | |
const paths = process.env.PATH.split(':'); | |
return paths | |
.map((dir) => Path.join(dir, name)) | |
.find((path) => isExecutable(path)); | |
} | |
function isExecutable(path) { | |
try { | |
const stats = FS.statSync(path); | |
if (!stats.isFile()) return false; | |
FS.accessSync(path, FS.constants.F_OK | FS.constants.X_OK); | |
return true; | |
} catch (err) { | |
if (['ENOENT', 'EACCES'].includes(err.code)) { | |
return false; | |
} | |
throw err; | |
} | |
} | |
const names = process.argv.slice(2); | |
names.forEach((name) => { | |
const path = getExecutablePath(name); | |
if (typeof path == 'undefined') { | |
console.log(`${name} not found`); | |
} else { | |
console.log(path); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will probably create an async version later.