Skip to content

Instantly share code, notes, and snippets.

@emmiep
Created March 27, 2018 12:16
Show Gist options
  • Save emmiep/775037095be001ddc123243a7990cf1a to your computer and use it in GitHub Desktop.
Save emmiep/775037095be001ddc123243a7990cf1a to your computer and use it in GitHub Desktop.
Node lookup executable in $PATH
#!/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);
}
});
@emmiep
Copy link
Author

emmiep commented Mar 27, 2018

Will probably create an async version later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment