NodeJs是前端開發工程師最熟悉不過的了,下面我就介紹一下如何爬取npm官網的包數據。javascript
npm init -y
複製代碼
cheerio
、request
和 request-promise
npm install cheerio && npm install request && npm insatll request-promise
複製代碼
index.js
文件,代碼以下const rp = require('request-promise');
const cheerio = require('cheerio');
const getNpmInfo = async ( packageName ) => {
const options = {
uri: 'https://www.npmjs.com/package/' + packageName,
transform: body => cheerio.load(body)
};
const $ = await rp(options);
let infoArray = [];
$('._9dMXo ._2_OuR').each(function() {
let key, value;
// find 方法獲取 key
key = $(this).find('._1IKXc').text();
// 下面兩個 key 裏面包含連接要單獨處理
if(key === 'repository' || key === 'homepage') {
value = $(this).find('.n8Z-E').find('.zE7yA').attr('href');
} else {
value = $(this).find('.n8Z-E').text();
}
infoArray.push({key, value});
})
console.log(infoArray);
// return infoArray;
}
getNpmInfo('webpack-dev-server');
// module.exports = getNpmInfo;
複製代碼
node index.js
複製代碼
會看到控制檯以下圖所示的內容前端
那麼問題來了...java
Node環境獲取的數據如何展現在瀏覽器環境裏?node
我能想到的辦法就是啓一個服務去接收這個方法,而後返回查詢到的值。webpack
express
npm install express --save
複製代碼
index.js
修改成以下,就是把這個方法暴露出去const rp = require('request-promise');
const cheerio = require('cheerio');
const getNpmInfo = async ( packageName ) => {
// ...
// console.log(infoArray);
return infoArray;
}
// getNpmInfo('webpack-dev-server');
module.exports = getNpmInfo;
複製代碼
api.js
,內容以下const express = require('express');
const getNpmInfo = require('./index');
const PORT = 8803;
const app = new express();
app.use('/', async function(req, res) {
res.send (await getNpmInfo(req.query.name))
})
console.log('Serve is run at ' + PORT + ' !')
app.listen(PORT);
複製代碼
node api.js
複製代碼
備註:固然若是想正式使用這個接口,那就要放在服務器上面。git
若是有什麼好的方法能夠解決數據可以在瀏覽器展現的問題,歡迎留言討論。web
敬上 git 地址: get-npm-package-info 求個🌟,謝謝express