Detailed explanation of basic nodejs operation methods

小云云
Release: 2023-03-21 18:30:02
Original
3332 people have browsed it


The previous project used PHP for high-frequency collection and settlement, which greatly reduced the efficiency of our PHP, and PHP blocking prevented our web pages from running normally. So find a language that can replace PHP for database operations and collection, and perfectly integrate with PHP.

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. Node.js's package manager npm is the world's largest open source library ecosystem.

First introduction to nodejs

nodejs, just like our PHP composer, you can use the npm command to download nodejs related plug-ins.
You can only use the front-end javascript to operate 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
Create a file that runs sql mysql.js

//连接数据库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();
Copy after login

Run the js. At this time, most functions can be implemented, including regular settlement functions, sharing the pressure of php, including collecting data

Make 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();
Copy after login

where var iconv = require('iconv-lite'); This module needs to be downloaded and introduced by npm to solve the problem The Chinese garbled code problem

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/gdkl@3x.png',
        shelves: 0,
        groupCode: 3,
        lotName: '广东快乐十分',
        totalCount: 84,
        serverTime: '2018-03-07 11:53:50',
        index: 100 } } }
Copy after login

The cheerio module is introduced to collect and process more complex data, and the 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');
});
Copy after login

combined with the operation of nodejs sql can insert the data into the database. Or other related operations

Use nodejs to make web pages and implement routing functions

Use npm to introduce express

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)

})
Copy after login

We visit 127.0 .0.1:8081 You can access the response page, or operate

The packaging of related operations of the database

Click to download the package file

Look first How to use

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

Take select as an example
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);
};
Copy after login

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();
}
Copy after login

How to reference a packaged js file

    var db = require('db'),
Copy after login

Summary: Database operation is 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改变了,多了一个参数cbfunction LazyAdd(a, cb){
    return function(b){
        cb(a, b);
    }
}//将Add传给形参cbvar result = LazyAdd(1, Add)// 这个时候去做一些其他的程序,等条件成立之后再去执行result = result(2); // => 3
Copy after login

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)
}
Copy after login

php side receives the nodejs delivery Information

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

Summary

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

The above is the detailed content of Detailed explanation of basic nodejs operation methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!