1.package.json
{ "name": "NODEZBJ", "version": "1.0.0", "description": "", " Main ":" Index.js ", " Scripts ": { " test ":" Echo \ "Error:no test specified\" && exit 1 " }, " author ":" ", " license ":" ISC ", " dependencies ": { "superagent": "3.5.1", "mysql": "2.13.0", "cheerio": "0.22.0" }}
2. Create a new sql.js inside Lib
varMySQL = require (' MySQL ');functionSQL (callback) {varConnection =mysql.createconnection ({host:‘‘, User:' Root ', Password:‘‘, Database:‘‘ }); Connection.connect (); Callback.call (NULL, connection); Connection.end ();} Module.exports={query:function(str, callback) {SQL (function(connection) {connection.query (str, callback); }); }};
3.node referencing MySQL
varRequest = require (' superagent ');varCheerio = require (' Cheerio '))var sql = require ('.. /lib/sql.js ' )request. Get ('/HTTP '). End (function(Err, res) {if(Err) {Console.log (err); return; } var$ =cheerio.load (Res.text); varCatediv = $ ('. List-category-nav. Unstyled.ui-dropdown-menu a '); Catediv.each (function(Index, item) {varText =$ (item). text (); varhref = $ (item). attr (' href ')); Console.log (text, href); Sql.query ( ' INSERT into cate1 (name, URL) VALUES ("' + text + '", "' + href + '") '); }); });
Node + MySQL