Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

1. Introduction of NodeJs

Nodejs is introduced

Node.js is a Javascript runtime environment. It allows JavaScript to develop back-end programs that do almost everything other back-end languages do, putting it on par with PHP, JSP, Python, Ruby, and other back-end languages. Nodejs is based on the V8 engine, the open-source JavaScript engine released by Google that is itself the JS interpretation part of Chrome, but Ryan Dahl, the guy who put V8 on the server, Software used to make servers.

Advantage of the Node

  1. NodeJs syntax is completely JS syntax, as long as you know the basics of NodeJs back-end development can learn to break the past JavaScript can only run in the browser situation. Unified front-end and back-end programming environment can greatly reduce the development cost.

  2. The primary goal of Node.js is to provide a simple development tool for creating high-performance servers and the kinds of applications that can run on them. In server-side languages such as Java, PHP, or.NET, a new thread is created for each client connection. Each thread consumes about 2MB of memory. That is, a server with 8GB of memory can theoretically connect to a maximum of around 4,000 users at the same time, and Node.js does not create a new thread for each client connection, but only uses one thread. When a user connects, an internal event is triggered, making Node.js programs macroscopically parallel through non-blocking I/O, event-driven mechanisms. With Node.js, a server with 8GB of ram, it can handle connections from over 40,000 users at the same time.

  3. Implement high-performance servers. Strictly speaking, Node.js is a development tool for developing various Web servers. On the node.js server, you run the high-performance V8JavaScript scripting language, which is a JavaScript scripting language that can run on the server side. So what is the V8 JavaScript scripting language? The language is a scripting language parsed and executed by the V8 JavaScript engine. V8JavaScript engine is a high-performance JavaScript engine developed by Google using C++ language, which is not limited to running in the browser. Node.js ADAPTS this to the server and provides it with a number of additional apis for various purposes. For example, in a server, you often need to deal with a variety of binary data. The Buffer class provided by Node.js provides a lot of binary data processing power, which is very limited in JavaScript. In addition, an entirely new compilation technique is used inside the V8 JavaScript engine. This means that the high end JavaScript script code written by a developer is very similar to the low end C script code written by a developer, which is an important feature that node.js servers can provide.

Build the Node environment

Nodejs website

NodeJs HTTP module and URL module

2.1 Node.js Creates the first application

If we use PHP to write back-end code, we need Apache or Nginx HTTP server to handle client requests accordingly. For Node.js, however, the concept is completely different. With Node.js, we’re implementing not just an application, but an entire HTTP server.

Introducing HTTP modules

var http = require("http");
Copy the code

Creating a Server

Next we create the server using the http.createserver () method and bind port 8888 using the Listen method. The function receives and responds to data using the request and response parameters.

var http = require('http');
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP status: 200: OK
// Set the HTTP header with the status code 200, the file type to HTML, and the character set to UTF8
response.writeHead(200, {"Content-Type":"text/html; charset=UTF-8"});
// Send response data "Hello World"
res.end("This is the first Node application.");
}).listen(3000);
Copy the code

To run the program

Switch to the corresponding directory of the program using the command line. Run the program through the node command.

node xxx.js
Copy the code

You’ll notice that if you write js locally, you can’t just drag it into the browser and run it, but with Node, you can run any JS file through Node. In other words, Node is a JS execution environment.

2.2 Using the HTTP Module

In Node.js, many functions are divided into modules. Many functions in Node.js are implemented through modules.

// Reference the module
var http = require("http");
// Create a server, and the callback represents what to do after receiving the request
var server = http.createServer(function(req,res){
	// The req parameter indicates the request, and the res parameter indicates the response
	console.log("The server received the request" + req.url);
	res.end(); The // End method causes the Web server to stop processing the script and return the current result
});
// Listen on the port
server.listen(3000);
Copy the code

Set a response header

// Reference the module
var http = require("http");
// Create a server, and the callback represents what to do after receiving the request
http.createServer(function(req,res){
	// The req parameter indicates the request, and the res parameter indicates the response
	res.writeHead(200, {"Content-Type":"text/html; charset=UTF8"});// Insert the response header
	console.log("The server received the request" + req.url);
	res.end(); The // End method causes the Web server to stop processing the script and return the current result
}).listen(3000);
Copy the code

Now let’s look at what you can use in REQ. The key is the req.url property, which represents the user’s request URL. All routing design is implemented through req.url. We’re not interested in getting the URL, we’re interested in identifying the URL. Identify the URL using the following URL module.

2.3 Use of URL module

const url = require('url');
url.parse()  / / URL
url.format(urlObject) // Is the reverse of the url.parse() operation above
url.resolve(from, to) // Add or replace the address
Copy the code

Small cases:

const http = require('http');
const url = require('url');

// Emulated client request address: http://127.0.0.1:8081/? name=%27test%27&age=12

http.createServer((req, res) = > {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  if(req.url ! ='/favicon.ico') {var userInfo = url.parse(req.url,true).query;

    console.log(` name:${userInfo.name}---年龄:${userInfo.age}`) // Name :'test'-- age :12
  }
  res.end('hello nodejs');
}).listen(8081);
Copy the code

3. Custom modules in CommonJs and Nodejs

What is Common. Js?

JavaScript is a powerful object-oriented language with many fast and efficient interpreters. However, the JavaScript standard defines apis for building browser-based applications. There is no standard library for a wider range of applications. The CommonJS specification was developed to compensate for the current lack of a standard for JavaScript. The ultimate goal is to provide a standard library of Python, Ruby, and Java languages, not just small scripts. CommonJS is the standard for modularity, and NodeJS is the implementation of CommonJS.

2.1 Modularity in Nodejs

Node applications are composed of modules that follow the CommonJS module specification.

  1. In Node, modules fall into two categories:

One is the module provided by Node, called the core module; The other is user-written modules, called file modules;

• Core module parts are compiled into binary executables during compilation of Node source code. When the Node process starts, part of the core module is directly loaded into the memory, so when this part of the core module is introduced, the two steps of file location and compilation execution can be omitted, and the priority judgment in the path analysis, so it is the fastest loading speed. For example, HTTP module, URL module, Fs module are the built-in core modules of NodeJS, which can be directly introduced and used.

• The file module is dynamically loaded at runtime, which requires complete path analysis, file location, compilation and execution process. The speed is slightly slower than the core module, but it is used very much. These modules need to be defined by ourselves.

  1. CommonJS (Nodejs) :

• We can separate common functions into a single JS file as a module. By default, methods or properties in this module are not accessible outside the module. To make methods or attributes accessible to the outside world, you must expose properties or methods inside the module through exports or module.exports.

• Introduce the module via require in files that need to use it. At this point you can use the properties and methods exposed in the module.

  1. Define usage modules:
// Define a tools.js module
// Module definition
var tools = {
	sayHello: function() {
		return 'hello NodeJS';
	},
	add: function(x, y) {	
		returnx + y; }};// Module interface exposed
// module.exports = tools;
exports.sayHello = tools.sayHello;
exports.add = tools.add;
Copy the code
var http = require('http');
// Introduce a custom tools.js module
var tools = require('./tools');
tools.sayHello(); // Use the module
Copy the code
  1. NPM init generates package.json

Package. json stores application information, such as version, dependencies, environment, etc

npm init 

eg:
{
  "name": "axios"."version": "1.0.0"."main": "axios.js".// Project entry
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": ""."license": "ISC"."keywords": []."description": ""
}
Copy the code
  1. A package directory that fully complies with the CommonJs specification generally contains the following files:

    Package. json: package description file;

    Bin: directory for storing executable binary files.

    Lib: a directory for storing JavaScript code;

    Doc: directory for storing documents;

4. NodeJs FS module

Introduce fs module before use

const fs = require('fs')
Copy the code

4.1 Fs. stat Checks whether it is a file or a directory

fs.stat('hello.js'.(error, stats) = >{
 if(error){
	console.log(error)
 } else {
	console.log(stats)
	console.log(` file:${stats.isFile()}`)
	console.log(` directory:${stats.isDirectory()}`)}})Copy the code

4.2 fs.mkdir Creating a directory

/** path Path of the directory to be created; Mode Directory permission (read/write permission), default 777; Callback, passing the exception parameter err; * * /


fs.mkdir('logs'.(error) = > {
 if(error){
	console.log(error)
 } else {
	console.log('Directory created successfully: logs')}})Copy the code

4.3 fs.writeFile creates a writeFile

/ * * filename (string) data file name (string | buffer) to be written content, can be a string or buffer data; Options (object) An option array object containing: Encoding (string) Optional value, default utF8 mode (number) File read and write permission, default 438 flag (string) Default 'w' callback {function} Callback, Pass an exception parameter, err **/

fs.writeFile('logs/hello.log'.'Hello ~ \n'.(error) = > {
 if(error) {
	console.log(error)
 } else {
	console.log('Write file successfully')}})Copy the code

4.4 fs.appendFile Appended files

fs.appendFile('logs/hello.log'.'hello ~ \n'.(error) = > {
 if(error) {
	console.log(error)
 } else {
	console.log('Write file successfully')}})Copy the code

4.5 fs.readFile Reads files

fs.readFile('logs/hello.log'.'utf8'.(error, data) = >{
	if (error) {
	   console.log(error)
	} else {
	  console.log(data)
	}
})
Copy the code

4.6 fs.readdir Reads a directory

fs.readdir('logs'.(error, files) = > {
	if (error) {
	  console.log(error)
	} else {
	  console.log(files)
	}
})
Copy the code

4.7 fs.rename Renames or moves a file

fs.rename('js/hello.log'.'js/greeting.log'.(error) = >{
	if (error) {
		console.log(error)
   } else {
	    console.log('Rename (move file) succeeded')}})Copy the code

4.8 fs.rmdir Deleting a directory

fs.rmdir('logs'.(error) = >{
	if (error) {
	   console.log(error)
	} else {
	   console.log('Successfully deleted directory: logs')}})Copy the code

4.9 fs.unlink Deleting a File

fs.unlink(`logs/${file}`.(error) = > {
	if (error) {
	   console.log(error)
	} else {
	   console.log('Successfully deleted file:${file}`)}})Copy the code

Mkdirp: a plug-in that creates directories and their subdirectories recursively in Node.js

4.10 fs.createreadStream Reads data from a file stream

const fs = require('fs')
var fileReadStream = fs.createReadStream('./test.txt')
let count = 0;
var str=' ';

fileReadStream.on('data'.(chunk) = > {
  console.log(`${ ++count }To receive:${chunk.length}`);
  str+=chunk
})

fileReadStream.on('end'.() = > {
  console.log('end -- -- -- -- -- --);
  console.log(count);
  console.log(str);
})

fileReadStream.on('error'.(error) = > {
  console.log(error)
})
Copy the code

4.11 fs.createWriteStream Writes files as file streams

var fs = require("fs");
var str = ' ';

for(let i = 0 ; i < 200; i++){
  str += 'I got the data from the database and I'm going to save it \n'
}
// Create a stream that can be written to the file output.txt
var writerStream = fs.createWriteStream('./output.txt');
// Write data using UTF8 encoding
writerStream.write(str,'UTF8');
// Mark the end of the file
writerStream.end();
// Process the stream event --> Finish event
writerStream.on('finish'.() = > { /* Finish - Triggered when all data has been written to the underlying system. * /
  console.log("Write complete");
}); 

writerStream.on('error'.(err) = > {
  console.log(err.stack);
});
Copy the code

4.12 the pipe flow

Pipes provide an output-to-input flow mechanism and are typically used to fetch data from one stream and pass it to another.

var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('./input.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('./output.txt');
// Pipe read and write operations
// Read the contents of input. TXT and write the contents to output. TXT
readerStream.pipe(writerStream);
console.log("Program completed");

// Copy compressed files, images, etc
var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('./test.zip');
// Create a writable stream
var writerStream = fs.createWriteStream('./test/testNew.zip');
// Pipe read and write operations
// Read the contents of input. TXT and write the contents to output. TXT
readerStream.pipe(writerStream);
console.log("Program completed");
Copy the code

5. Non-blocking IO, asynchronous, event-driven basics

5.1 Single-threaded non-blocking I/O event drivers

In server-side languages such as Java, PHP, or.NET, a new thread is created for each client connection. Each thread consumes about 2MB of memory. In other words, the maximum number of users that can be connected to a server with 8GB of memory is about 4000. To enable Web applications to support more users, the number of servers needs to increase, and the hardware cost of Web applications certainly goes up. Instead of creating a new thread for each client connection, Node.js uses only one thread. When a user connects, an internal event is triggered, making Node.js programs macroscopically parallel through non-blocking I/O, event-driven mechanisms. With Node.js, a server with 8GB of ram, it can handle connections from over 40,000 users at the same time.

5.2 Nodejs callback processing asynchronous

// Handle asynchrony correctly:
function getData(callback){
  // Simulate request data
  var result = ' ';
  setTimeout(function(){
    result = 'Here's the requested data.';
    callback(result);
  },200);
}

getData(function(data){
  console.log(data);
})
Copy the code

5.3 Nodejs Events module handles asynchrony

Node.js has several built-in events, and we can bind and listen to events by introducing the Events module and instantiating the EventEmitter class.

// Introduce the events module
var events = require('events');
var EventEmitter = new events.EventEmitter(); /* Instantiate the event object */

EventEmitter.on('toparent'.function(){
  console.log('Broadcast event received');
})

setTimeout(function(){
  console.log('radio');
  EventEmitter.emit('toparent'); /* Send broadcast */
},1000)
Copy the code