UNPKG

alinex-fs

Version:

Extension of nodes filesystem tools.

117 lines (99 loc) 2.94 kB
/* Find Binary ================================================= This will search a binary in the NPM modules directories. Find the defined binary in node_modules directories. It will search in the current and upper package directories. __Example:__ ``` coffee fs = require 'alinex-fs' fs.npmbin 'coffee', (err, cmd) -> console.log "Coffee command found at:" + cmd ``` */ (function() { var debug, fs, npmbin, npmbinSync, path; fs = require('fs'); path = require('path'); debug = require('debug')('fs:npmbin'); /* @param {String} bin name of the binary to search for @param {String} dir directory to start search from @param {function(<Error>, <String>)} cb callback with an `Error` or the found binary's path */ module.exports.npmbin = function(bin, dir, cb) { if (debug.enabled) { debug("Search binary " + bin + " starting at " + dir); } return npmbin(bin, dir, cb); }; /* @param {String} bin name of the binary to search for @param {String} dir directory to start search from @return {String} the found binary's path @throws {Error} if binary could not be found */ module.exports.npmbinSync = function(bin, dir) { if (debug.enabled) { debug("Search binary " + bin + " starting at " + dir); } return npmbinSync(bin, dir); }; npmbin = function(bin, dir, cb) { var file; if (!cb) { cb = dir; dir = path.dirname(__dirname); } file = path.join(dir, 'node_modules', '.bin', bin); return fs.exists(file, function(exists) { var i, len, parent, ref; if (exists) { if (debug.enabled) { debug("-> found at " + file); } return cb(null, file); } parent = path.join(dir, '..', '..'); if (parent === dir) { ref = process.env.PATH.split(/:/); for (i = 0, len = ref.length; i < len; i++) { dir = ref[i]; file = path.join(dir, bin); if (fs.existsSync(file)) { return cb(null, file); } } return cb(new Error("Could not find " + bin + " program.")); } return npmbin(bin, parent, cb); }); }; npmbinSync = function(bin, dir) { var file, i, len, parent, ref; if (dir == null) { dir = path.dirname(__dirname); } file = path.join(dir, 'node_modules', '.bin', bin); if (fs.existsSync(file)) { if (debug.enabled) { debug("-> found at " + file); } return file; } parent = path.join(dir, '..', '..'); if (parent === dir) { ref = process.env.PATH.split(/:/); for (i = 0, len = ref.length; i < len; i++) { dir = ref[i]; file = path.join(dir, bin); if (fs.existsSync(file)) { return file; } } throw new Error("Could not find " + bin + " program."); } return npmbinSync(bin, parent); }; }).call(this); //# sourceMappingURL=npmbin.map