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