Detailed explanation of basic nodejs operation methods
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();
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();
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 } } }
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'); });
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) })
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) { //查询成功之后相关操作 } ,})
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); };
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 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
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) }
php side receives the nodejs delivery Information
public function nodejs_get_data(){ $data= json_decode(file_get_contents('php://input'),true); //对$data数据的相关操作 }
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!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version