node + mysql

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.在 lib 里面新建 sql.js

var mysql = require('mysql');

function SQL(callback) {
    var connection = 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 引用 mysql

var request = require('superagent');
var cheerio = 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);
        var cateDiv = $('.list-category-nav .unstyled.ui-dropdown-menu a');

        cateDiv.each(function(index, item) {
            var text = $(item).text();
            var href = $(item).attr('href');
            console.log(text, href);
            sql.query('INSERT INTO cate1 (name, url) VALUES ("' + text + '", "' + href + '")');
        });

    });

 

posted @ 2017-03-20 18:16  桔子木木  阅读(200)  评论(0编辑  收藏  举报