"The ancients' knowledge is weak, but their Kung Fu can only be achieved when they are young and old."
One article takes you from the introduction to the mastery of nodejs. In fact, the cost of learning nodejs is not so high. You only need this article from brother feitu. Ten minutes will take you from the introduction to the mastery. I hope if you think this article can bring you some help, I hope to give brother feitu a key three times to express support. Thank you~
catalogue
1, Installation and simple use
5, Install the mime module and use
Vi. module for managing npm source
7, Switch nodejs version using NVM
8, Automatic restart and date processing module
Xi. Release of customized module package
1, Installation and simple use
- Download address 1: http://nodejs.cn/download
- Download address 2: https://nodejs.org/zh-cn/download
- After the installation is completed, use the {node -v} command in the black window to check whether the installation is successful
- We use node to enter the hello world string
- command
# Enter node environment node # Output hello world console.log('hello world')
2, Custom module
- A custom module is to define its own methods and then introduce them where needed
- We create a say JS file, write the following
- command
function say(){ console.log("hello world!"); } exports.say = say;
- When you need to use this say method in a file
- You can import using the following methods
- command
var res = require("./say"); res.say();
3, node built-in module
- os system module
var os = require("os"); Line feed: os.EOL Host name: os.hostname(); Operating system: os.type(); Operating platform: os.platform(); Total memory(byte): os.totalmem(); idle memory(byte): os.freemem();
- path module
var path = require("path"); var filepath ="https://www.xxxx.cn/wechat/wechatpay.php"; File name: path.basename(filepath); Directory name: path.dirname(filepath);
- url module
var url = require("url"); var data ="https://www.jiangliang738.cn?name=eden&age=24"; url.parse(data); Become object: $info = url.parse(data,true); Get parameters: $info.query
- fs file module
var fs = require("fs"); fs.writeFile(Path and file name, "utf8", function(err, data){ if(!err){ console.log(data); } });
- http module
var http = require("http"); #Create web server var server = http.createServer(); #Listening request server.on('request',function(req,res){ console.log("Request received"+req.url); res.setHeader("Content-Type","text/html;charset=utf-8"); res.write("Hello nodejs"); res.end(); }) #Start service server.listen(8080,function(){ console.log("Service started successfully"); })
4, npm command line tool
- npm is a command-line tool used to manage modules. You can download and import any modules you need
- Module website: https://www.npmjs.com
- Downloading nodejs will automatically install the npm tool
- npm has some common commands, as follows
- command
npm -v # View npm version npm list # See which modules are installed npm init -y # initialization npm install [modular] # Installation module npm uninstall [modular] # Uninstall module
5, Install the mime module and use
- For example, we need to install the mime module
- command
npm -i mime [-g]
- Detailed explanation of installation parameters
- -g this module can be run on the command line
- --save records the modules required by the production environment
- --Save dev records the modules required by the development environment
- Using the mime module
//Introduction module var mime = require("mime"); //Determine file type var img = "xxxx.png"; console.log(mime.getType(img)); console.log(mime.getExtension("image/png"));
Vi. module for managing npm source
- Because npm is used to download and manage modules
- npm must be active. If the source address is abroad, you will find that the download is very slow. At this time, we have to switch the source
- The module that manages npm sources is called nrm
- command
# Install nrm npm install nrm [-g] # View source address list nrm ls # Switch address nrm use server name # velocity measurement nrm test
7, Switch nodejs version using NVM
- To manage the version of nodejs, you need to use the nvm service
- nvm service needs to be installed first
- nvm has many common commands as follows
- command
#View version nvm version #Install the latest version nvm install latest nvm install Version number nvm uninstall Version number # View all nodejs versions nvm list #Switch to new version nvm use Version number
8, Automatic restart and date processing module
-
Our common modules are automatic restart and date processing
-
If we want to modify mime Any content in JS can see the effect immediately, instead of taking effect after restarting manually
-
command
# Install the automatic restart module npm install nodemon [--save-dev -g] # use nodemon mime.js
- For more time module operations, please see the documentation: http://momentjs.com
- command
# Installation time module npm install moment # use var moment = require('moment'); console.log( moment().format() );
9, Web crawler
- node can be crawled, and the cherio module needs to be used
- This module can be understood as jq of node version, which is used to obtain web page data
- command
# install npm i cheerio
# Basic use of this module var http = require("http"); http.get("website", function(req,res){ #Used to save web page data var html=''; req.on("data",function(data){ html +=data; }) req.on("end",function(){ getTittle(html) }) }) function getTittle(html){ #Introduction of crawler module const cheerio = require("cheerio"); #Encapsulate the obtained html code into a $object const $ = cheerio.load(html,{decodeEntities:false}); #Matching data $('selector').each(function(index,item){ console.log($(item).html()); }); }
10, Database operation
- node can be listed as a back-end language because it can manipulate databases
- To operate the database, we need to install the mysql module. For more information, please refer to the document: https://www.npmjs.com/package/mysql
- command
# Installation module npm i mysql
# Basic use var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', # Database host user : 'me', # Database account password : 'secret', # Database password database : 'my_db' # database }); connection.connect(); connection.query('mysql sentence', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); }); connection.end();
Xi. Release of customized module package
- In the above, we all use other people's modules downloaded by npm, so how to define our own package and put it on the website for others to use
- We need to encapsulate our package and upload it to https://www.npmjs.com Website, package management, you can let others download
- First of all, we need to register our own account on this website. We need to have our own account
- command
# Create a local folder and initialize it npm init -y # Configure package JSON parameter { "name": "mydemo", # Project name, such as mysql above "version": "1.0.0", "description": "this is a package", # Project description "main": "index.js", "scripts": { "test" : "echo \"Error: no test specified\" && exit 1" }, "keywords": ["nodejs", "php"], "author": "autofelix", "license": "ISC" } # In index JS package code function say(){ console.log("hello npm"); } exports.say = say; # nrm can only be published after switching to a foreign server nrm ls nrm use npm # Log in to your account and enter your account, password and email npm login # Upload to warehouse npm publish
12, Express framework
- This is a node module. This module is used to develop websites, making website development easy
- command
# initialization npm init -y # Install the frame module npm install express
- Basic use
#Introduction module var express = require("express"); #Create server var app = express(); #Listening request app.get("/", function(req, res){ //end() response string (garbled) //send() response string (automatic recognition) //render() response string (automatic recognition, specifying the string in the file) }); #Start service app.listen(8080,function(){ console.log("Start successful"); })
- Because end and send cannot resolve the template
- Therefore, we need to use the template engine art module. For more use of the template, please refer to: https://aui.github.io/art-template/zh-cn/docs/index.html
- Command
# Install template engine npm install art-template npm install express-art-template
- Advanced use
- Because the render method calls the views under the root directory by default, you need to create the directory manually
#Introduction module var express = require("express"); #Create server var app = express(); #Configuration engine app.engine("html", require('express-art-template')); #Listening request app.get("/", function(req,res){ //end() response string (garbled) //send() response string (automatic recognition) //render() response string (automatic recognition, specifying the string in the file) res.render("test.html"{ [Parameter 1]: [Value 1], [Parameter 2]: [Value 2], [Parameter 3]: [ {id:1,title:"Title 1"}, {id:2,title:"Title 2"}, {id:3,title:"Title 3"} ], }) }); #Start service app.listen(8080,function(){ console.log("Start successful"); })
- Routing in framework
#get route app.get(Request path, callback function); #post routing app.post(Request path, callback function); #Arbitrary request app.all(Request path, callback function); app.use(Request path, callback function);
- Static resource hosting
#Allows files in the specified directory to be accessed externally #Syntax: Express Static ("directory name") app.use("/public",express.static("public"));
- Template loop syntax
{{each orders as order index}} {{/each}}
13, KOA2 framework
- Built by the original team of express framework
- Document address: https://www.npmjs.com/package/koa-art-template
- command
# Installing the frame generator koa generator npm install koa-generator -g # Generating stu projects through koa generator koa2 stu # Install framework dependent framework (default, module engine, database, etc.) cd stu && npm install npm install art-template koa-art-template mysql