nodejs basic operation learning and sharing meeting in March

understand nodejs

Node.js is a JavaScript runtime environment based on the Chrome V8 engine.
Node.js uses an event-driven, non-blocking I/O model, making it lightweight and efficient.
npm, the package manager for Node.js, is the world's largest ecosystem of open source libraries.

purpose of learning

The previous project used php for high-frequency collection and settlement, which greatly reduced the efficiency of our php, and php blocking made our web pages unable to run normally. So find a language that can replace php to operate database and collect, and combine it perfectly with php.

Getting to know nodejs for the first time

nodejs, like our php composer, can use npm command to download nodejs related plugins.
Using the front-end javascript can only operate the basic functions, and the cost of learning is greatly reduced.

normal operation

nodejs link database

At this time, we will rely on npm to download the mysql module,
switch to our project, npm install mysql -save
to create a file mysql.js that runs sql

//连接数据库
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database:'carbird'
});

connection.connect();
//查询
connection.query('select * from `think_order`', function(err, rows, fields) {
    if (err) throw err;
    console.log('查询结果为: ', rows);
});
//关闭连接
connection.end();

Run the js, most of the functions can be realized at this time, the regular settlement function, sharing the pressure of php, including collecting data

Do an example of nodejs collecting 1680210 lottery tickets and storing them in the database

Create pacong.js

var http = require("http");
var iconv = require('iconv-lite');
var option = { 
hostname: "api.api68.com",
path: "/klsf/getLotteryInfo.do?issue=&lotCode=10005"
}; 
var req = http.request(option, function(res) {
res.on("data", function(chunk) {
console.log(JSON.parse( iconv.decode(chunk, "utf-8") ));
}); 
}).on("error", function(e) {
console.log(e.message);
});
req.end();

Where var iconv = require('iconv-lite'); This module needs to be downloaded and imported by npm to solve the problem of Chinese garbled characters

The result is:

{ errorCode: 0,
  message: '操作成功',
  result:
   { businessCode: 0,
     message: '操作成功',
     data:
      { preDrawIssue: 2018030717,
        preDrawCode: '03,13,10,11,01,18,07,12',
        drawIssue: 2018030718,
        drawTime: '2018-03-07 12:01:20',
        preDrawTime: '2018-03-07 11:51:20',
        drawCount: 17,
        firstDragonTiger: 1,
        lastBigSmall: 0,
        sumBigSmall: 1,
        sumNum: 75,
        sumSingleDouble: 0,
        fourthDragonTiger: 0,
        secondDragonTiger: 0,
        thirdDragonTiger: 1,
        frequency: '',
        lotCode: 10005,
        iconUrl: 'http://webapp.1680180.com/images/icon/3x/[email protected]',
        shelves: 0,
        groupCode: 3,
        lotName: '广东快乐十分',
        totalCount: 84,
        serverTime: '2018-03-07 11:53:50',
        index: 100 } } }

Introduce cheerio module to collect and process, more complex data, crawler website

var express = require('express');
var app = express();
var request = require('request');
var cheerio = require('cheerio');

app.get('/', function(req, res) {

  request('http://www.zhongjiantang.com/index.php?c=detail&id=57', function(error, response, body) {
    if (!error && response.statusCode == 200) {
      $ = cheerio.load(body);
      res.json({
          cat: $('h1').text()
      });
    }
  })
});

var server = app.listen(3000, function() {
  console.log('listening at 3000');
});

Combined with the operation of nodejs sql, data can be inserted into the database, or other related operations

Use nodejs to make web pages and implement routing functions

Introduce express with npm

Create a web.js

var express = require('express');
var app = express();

//  主页输出 "Hello World"
app.get('/', function (req, res) {
   console.log("主页 GET 请求");
   res.send('Hello GET');
})


//  POST 请求
app.post('/', function (req, res) {
   console.log("主页 POST 请求");
   res.send('Hello POST');
})

//  /del_user 页面响应
app.get('/del_user', function (req, res) {
   console.log("/del_user 响应 DELETE 请求");
   res.send('删除页面');
})

//  /list_user 页面 GET 请求
app.get('/list_user', function (req, res) {
   console.log("/list_user GET 请求");
   res.send('用户列表页面');
})

// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/ab*cd', function(req, res) {   
   console.log("/ab*cd GET 请求");
   res.send('正则匹配');
})


var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("应用实例,访问地址为 http://%s:%s", host, port)

})

We can access the response page by visiting 127.0.0.1:8081, or operate

Subpackage of database related operations

Click to download package file

First see how to use

        db.select({
            table: '数据表',
            where: '字段名称='查询条件',
            success: function (result) {
                   //查询成功之后相关操作
                }
                ,})

Take select as an example to
create sql:

exports.select = function(obj){
    if(!obj){
        log('对象不存在');
        return;
    }
    if(!obj.hasOwnProperty('field')){
        obj.field ="*";
    }
    var Sql = 'SELECT '+obj.field+' FROM '+obj.table ;
    if(obj.hasOwnProperty('where')){
        Sql+=' WHERE '+obj.where;
    }
    if(obj.hasOwnProperty('limit')){
        Sql+=' LIMIT '+obj.limit;
    }
    // console.log(Sql);
    db_query(Sql,obj);
};

Execute sql:

function db_query(Sql,obj){
    var db_client=mysql.createClient(config.dbinfo);
    db_client.query(Sql,function(err,data){
        if(err){
            if(obj.error){
                if(obj.hasOwnProperty('error')){
                    obj.error(err);
                }
            }else{
                log('数据库出错:' + err.message);
            }
        }else{
            if(obj.hasOwnProperty('success')){
                obj.success(data);
            }
        }
        if(obj.hasOwnProperty('callback')){
            obj.callback(err,data);
        }
    });
    db_client.end();
}

How to reference a packaged js file

    var db = require('db'),

Summary: Database operations are an asynchronous process. It can greatly improve the work efficiency of nodejs, and at the same time

Analyze an asynchronous example

//代码示例3
//注意还是那个Add,精髓也在这里,随后说到
function Add(a, b){
    return a+b;
}
//LazyAdd改变了,多了一个参数cb
function LazyAdd(a, cb){
    return function(b){
        cb(a, b);
    }
}
//将Add传给形参cb
var result = LazyAdd(1, Add)
// 这个时候去做一些其他的程序,等条件成立之后再去执行
result = result(2); // => 3

How nodejs sends data to php through http

function requestKj(number) {
    var postData = JSON.stringify(number);
    var option = {
        host: 网址,
        path: 地址,
        method: 'POST',
        headers: {
            "Content-Type": 'application/json',
            "Content-Length": Buffer.byteLength(postData)
        }
    };
    var req = http.request(option, function (res) {
        res.on('data', function () {
        });
        res.on('end', function () {
            console.log('成功前端给php');
        });
    });
    req.write(postData);
    req.end();
    setTimeout(function () {
        yuegengxin(number);
    },1000)
}

The php side receives the information passed by nodejs

    public function nodejs_get_data(){
        $data= json_decode(file_get_contents('php://input'),true);
        //对$data数据的相关操作
    }

Summarize

Nodejs is still the tip of the iceberg and has a lot to learn.
nidejs collection Api demo
nodejs great blog tutorial

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326078045&siteId=291194637