Skip to content

Instantly share code, notes, and snippets.

@rksm
Created June 4, 2013 02:25
Show Gist options
  • Save rksm/5703150 to your computer and use it in GitHub Desktop.
Save rksm/5703150 to your computer and use it in GitHub Desktop.
using npm programmatically
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