Created
June 4, 2013 02:25
-
-
Save rksm/5703150 to your computer and use it in GitHub Desktop.
using npm programmatically
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
function withNPMDirDo(func) { | |
exec('npm bin -g', function(code, out, err) { | |
var npmBinDir = String(out).trim(), | |
npmlibDir = path.join(npmBinDir, '..', 'lib', 'node_modules', 'npm'); | |
func(null, npmlibDir); | |
}); | |
} | |
npmDo = function npmDo(/*command, orgs..., callback*/) { | |
var args = Array.prototype.slice.call(arguments), | |
cmd = args.shift(), | |
cb = typeof args[args.length-1] === 'function' ? args.pop() : function(err, result, current) {}; | |
withNPMDirDo(function(err, npmDir) { | |
var npm = require(npmDir), | |
npmconf = require(path.join(npmDir, "node_modules", "npmconf")), | |
nopt = require(path.join(npmDir, "node_modules", "nopt")), | |
configDefs = npmconf.defs, | |
shorthands = configDefs.shorthands, | |
types = configDefs.types, | |
conf = nopt(types, shorthands); | |
npm.prefix = someDir; // FIXME how to correctly set cwd for npm? | |
npm.load(conf, function (er) { | |
if (er) { process.stderr.write(er); return } | |
try { | |
npm.commands[cmd](args, cb); | |
} catch(e) { | |
cb(e); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment