forked from marcbachmann/npm-module-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (43 loc) · 1.28 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var findInBatches = require('find-in-batches')
var request = require('request')
var cheerio = require('cheerio')
exports.search = function (query, options, callback) {
if (arguments.length === 2) {
callback = options
options = {}
}
query = (query || '').trim()
if (!query) return callback(null, [])
var opts = { batchSize: 20, maximum: 20 }
if (options.limit) opts.maximum = options.limit
var modules = []
findInBatches.each(opts, function find (options, callback) {
search(query, options, callback)
}, function each (m, done) {
modules.push(m)
done()
}, function (err) {
if (err) return callback(err)
callback(null, modules)
})
}
function search (query, options, callback) {
var page = options.page || 1
return request({
method: 'get',
url: 'https://www.npmjs.com/search?page=' + page + '&q=' + query
}, function (err, res, body) {
if (err) return callback(err)
var $ = cheerio.load(body)
var modules = []
$('.package-details').each(function () {
modules.push({
name: $(this).find('.packageName').text(),
version: $(this).find('.version').text(),
author: $(this).find('.authorName').text(),
description: $(this).find('.description').text()
})
})
callback(null, modules)
})
}