Table of Contents
First introduction to nodejs
Normal operation
Make an example of nodejs collecting 1680210 lottery tickets and storing them in the database
The cheerio module is introduced to collect and process more complex data, and the crawler website
Use nodejs to make web pages and implement routing functions
How nodejs sends data to php through http
php side receives the nodejs delivery Information
Summary
Home Backend Development PHP Tutorial Detailed explanation of basic nodejs operation methods

Detailed explanation of basic nodejs operation methods

Mar 20, 2018 am 11:08 AM
javascript nodejs Basic operations


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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

See all articles