var cheerio = require('cheerio');
var iconv = require('iconv-lite');
var https= require('https');
var mysql = require('mysql');
// 创建连接
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '12345678',
database : 'testmysql'
});
connection.connect();
var bookList = [];
var Bindex = 0;
function zhihuin(Bindex, index) {
console.log(Bindex);
return new Promise(function (resolve, reject) {
var addSql = 'INSERT INTO zhihuNum(Id, name, num) VALUES(?,?,?)';
var addSqlParams = [Bindex, bookList[index].name, bookList[index].num];
// 这个连接也是异步的
connection.query(addSql, addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
reject(0);
}else {
resolve(1);
}
});
})
}
function zhihuinnum(Bindex, index) {
zhihuin(Bindex, index).then(function (data) {
Bindex++;
index++;
if(index < bookList.length){
zhihuinnum(Bindex, index);
}else {
connection.end();
}
},function (data) {
index++;
if(index < bookList.length){
zhihuinnum(Bindex, index);
}else {
connection.end();
}
})
}
function zhihunum(){
var sql = 'SELECT works FROM zhihuBook';
//查
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}else {
for(let item of result){
if(item.works != ''){
// console.log(item.works.trim().split(/\s+/));
var bookwork = item.works.match(/《.*?》/g);
// console.log(bookwork)
for (let ilist of bookwork){
if(bookList.length == 0){
bookList.push({'name': ilist, 'num': 1});
}else {
var i = 0;
for(i = 0; i < bookList.length; i++){
if(ilist == bookList[i].name){
console.log(ilist, bookList[i].name)
bookList[i].num++;
break;
}
}
if(i >= bookList.length){
bookList.push({'name': ilist, 'num': 1});
}
}
}
}
}
// console.log(bookList);
bookList = bookList.sort((x, y)=>{
if(x.num < y.num){
return 1;
}else if(x.num > y.num){
return -1;
}else{
return 0;
}
});
zhihuinnum(0, 0);
}
});
}
zhihunum();
// connection.end();
1、数组的排序函数sort
bookList = bookList.sort((x, y)=>{
if(x.num < y.num){
return 1;
}else if(x.num > y.num){
return -1;
}else{
return 0;
}
});
接受两个参数,都是数组中的元素,第二个参数在数组中的序列是在第一个参数后面,函数体中,返回正数,表明两个元素交换位置,返回0,表明相等。返回负数,表明不交换位置。