From aad1c17c9a9407805a0e4ca1b1cc0d6f2139ce68 Mon Sep 17 00:00:00 2001 From: "Howard.Zuo" Date: Wed, 7 Jun 2017 17:25:06 +0800 Subject: [PATCH] add registry specifying support --- README.md | 7 +++++++ index.js | 30 +++++++++++++++++++++--------- test.js | 13 +++++++++++++ 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index acc5af3..c176779 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,13 @@ var getPkg = require('get-pkg'); getPkg('generate', function(err, pkg) { console.log(pkg); }); + +//specify a registry +getPkg('generate', { + registry: 'https://registry.npm.taobao.org/' +}, function(err, pkg) { + console.log(pkg); +}); ``` ## Related projects diff --git a/index.js b/index.js index bd6b6dc..70dfdc1 100644 --- a/index.js +++ b/index.js @@ -9,21 +9,33 @@ var request = require('min-request'); -module.exports = function getPkg(name, version, cb) { - if (typeof version === 'function') { - cb = version; - version = ''; +var OFFICIAL_REGISTRY = 'https://registry.npmjs.org/'; + +module.exports = function getPkg(name, opts, cb) { + if (typeof opts === 'function') { + cb = opts; + opts = { + version: '', + registry: OFFICIAL_REGISTRY + }; + } + + if (!opts.registry) { + opts.registry = OFFICIAL_REGISTRY; + } else if (opts.registry.lastIndexOf('/') !== opts.registry.length - 1) { + opts.registry = opts.registry + '/'; } + if (isScoped(name)) { name = '@' + encodeURIComponent(name.slice(1)); - version = ''; // npm does not allow version for scoped packages - } else if (!version) { - version = 'latest'; + opts.version = ''; // npm does not allow version for scoped packages + } else if (!opts.version) { + opts.version = 'latest'; } - var url = 'https://registry.npmjs.org/' + name + '/'; + var url = opts.registry + name + '/'; - request(url + version, {}, function(err, res) { + request(url + opts.version, {}, function(err, res) { if (err) return cb(err); if (res.statusCode === 500) { return cb(new Error(res.statusMessage)); diff --git a/test.js b/test.js index 4cae32b..e715989 100644 --- a/test.js +++ b/test.js @@ -45,4 +45,17 @@ describe('getPackages', function() { cb(); }); }); + + it('should handle specific registry', function(cb) { + getPkg('angular', { + registry: 'https://registry.npm.taobao.org/' + }, function(err, pkg) { + assert(!err); + assert(pkg); + assert.equal(pkg.name, 'angular'); + cb(); + }); + }); + + });