This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.

This is a comprehensive introduction to Node usage and all aspects, and aims to be detailed and concise enough to get you started. If have a question welcome to correct or criticize!

The introduction and popularity of Node is no longer described, directly roll up the sleeves, the actual use of Node, first from its concept and basic use start!

The Node is introduced

NodeJs website

Based on V8 engine development, Node enables JavaScript to run out of the browser, making it possible to write Web server background applications and even now, desktop applications (Electron… React Native, Uni-app… The market also began to be OCCUPIED by JS.

Front-end engineering tools such as Webpack, Gulp, and Npm rely on Node. Node is also widely used in middle-tier servers, responsible for I/O read and write, data query, and so on.

Node.js is JavaScript that runs on the server and is a platform built around the Chrome JavaScript runtime.

Node.js is an event-driven I/O server-side JavaScript environment, based on Google’s V8 engine, which executes JavaScript very fast and performs very well. Coupled with the booming development of the front-end, JS has gradually developed into a full stack, full end language, which makes Node so popular!

The Node using

Download and install

From nodejs. Cn/download/cu… Download the latest Nodejs version. The latest long-term support version is V14.17.5.

Select the corresponding version to download.

After downloading. Double-click to run setup:

Select the installation path:

In custom installation, select the required items. Usually keep the default, select either:

Do not check the tools required for automatic installation:

Install Wait until the installation is complete:

View the version and run the JS file

> node - v v14.17.0Copy the code

Enter the Node environment to run js and js files

Command, type node, press Enter:

> node Welcome to node.js v14.17.0.type".help" for more information.
> let a=1;
undefined
> a+1
2
> a++
1
> a
2
> .exit
Copy the code

To exit the Node environment, use the. Exit command. Or Ctrl+D, or Ctrl+C twice.

Execute a js file. File console.log(“Hello World! ); .

In the directory where the test.js file resides, start the command tool CMD or powershell. As follows:

> node test.js
Hello World!
> node test
Hello World!
Copy the code

Node Package Manager (NPM) Package Manager

The NPM command is used with CNPM

When using and developing Nodejs projects, NPM is often used to manage the packages used and the dependencies between them.

The following is an introduction and use of the multi-NPM command.

  • npm initTo initialize a project.
  • npm install -g cnpm --registry=https://registry.npm.taobao.orgInstall CNPM, CNPM is the domestic mirror of NPM (Taobao), basically keep synchronization with NPM, domestic use can be exempted from network connection restrictions.
  • cnpm i packagenameorcnpm install packagename, install a package.

To install jquery: CNPM I jquery

The new NPM install simply downloads the node package to the node_modules folder and does not add it as a dependency to package.json.

  • cnpm un packagenameorcnpm uninstall packagenameFrom packagenode_modulesRemove folder under and deletepackage.jsonCorresponding dependencies.
  • cnpm i packagename -S: installs the package and adds it topackage.jsonIs dependent on.
  • cnpm i packagename -D: installs the package and adds it topackage.jsonDevelopers rely on.
  • npm update xxxUpdate a package.
  • Run directlycnpm iorcnpm install, you can install all dependencies in package.json

Package. json file, which contains the package information used (Node or JS libraries, frameworks, etc.) to manage the required packages and package dependencies. When you install a package through NPM Install, you can specify which dependency to install under, which modifies the contents of package.json and maintains the package and its dependencies.

Package dependency classification

Development dependencies: devDependencies

Development environment dependencies, second only to Dependencies! The object definition of Dependencies is the same as that of Dependencies, except that the package is used only in the development environment and not in the production environment. These packages are usually unit tests or packaging tools, such as Gulp, Grunt, Webpack, Moca, coffee, etc

  • Installation command:
npm install package-name --save-dev
Copy the code

or

npm install package-name -D
Copy the code

Produce dependencies: dependencies

Application dependencies, or business dependencies, are the most common dependency package managed object! It is used to specify external packages that the application depends on, which are required for normal application execution after publication, but do not include packages used for testing or local packaging.

  • Install command
npm install package-name --save
Copy the code

or

npm install package-name -S
Copy the code

See NPM –02– Development and production dependencies

It is recommended that you use the Yarn package manager for future Node projects. The following articles will describe Yarn in detail.

Node in the case of multiple system users

After node is installed, switch to another user and run the node -v and NPM -v command to obtain the correct version.

However, modules installed globally through NPM cannot be obtained and run from the command line.

The solution is to reinstall the node or repair the installed node.

If NPM is still unavailable after installing Node, the solution again is to add the %APPDATA%\ NPM path to the user’s environment variable, such as Administrator: C:\Users\Administrator\AppData\Roaming\ NPM, Add environment variable

You can also add it directly to the system’s PATH environment variable.

The Node of the module

The callback function

Let’s start with Node’s callback functions. Therefore, when writing or importing modules in Node, there are often many callbacks.

Callbacks are an implementation of asynchronous programming in JavaScript, and you’ll find a lot of them in Node or JS.

The so-called callback function is to write the second part of the task in a separate function. When the second part of the task needs to be executed, the function is called directly.

Node specifies that the first argument to the callback must be the error object err (null if there are no errors).

The reason is that the execution is divided into two parts, and by the end of the first part, the context in which the task is executed is over. Errors thrown after this point cannot be caught in the original context and can only be passed as arguments to the second paragraph.

Asynchronous application of Generator functions

Global module (object)

It can be accessed anytime, anywhere, without reference. As a process.

process.envThe environment variable

For example, output different content according to different environment variables:

// process.env.dev=true;
if(process.env.dev){
    console.log("I'm the development environment");
}
else{
    console.log("I'm the production environment");
}
Copy the code

process.argvInput commands and parameters

Create the test.js file as follows:

console.log(process.argv);

let num1=parseInt(process.argv[2]);
let num2=parseInt(process.argv[3]);
console.log(num1+num2);
Copy the code

Perform:

>node test20 and 40 ['C:\\Program Files\\nodejs\\node.exe'.'E:\ vscode\ Node contact \Node contact with 1\\test'.'20'.'40'
]
60
Copy the code

__dirnameThe path name

__dirname is used to get the path of the output file currently executing.

Bufferobject

A Buffer object is an interface for Node to process binary data. It is a global object natively provided by Node and can be used directly.

A Buffer represents a Buffer that is primarily used to manipulate binary data streams. Is an array-like object whose members are one byte of 8 bits (integer values 0 to 255).

  • Buffer object usage

As follows, instantiate a Buffer object and assign a value to it.

// Generate a 256-byte Buffer instance
var bytes = new Buffer(256);

// Iterate over each byte and write
for (var i = 0; i < bytes.length; i++) {
  bytes[i] = i;
}


// Generate a buffer view
// Fetch from 240 bytes to 256 bytes
var end = bytes.slice(240.256);

end[0] / / 240
end[0] = 0;
end[0] / / 0
Copy the code
  • Buffer to copy

The copy method copies bytes members 4 through 7 to the area starting from 0 of the more instance as follows.

var bytes = new Buffer(8);

for (var i = 0; i < bytes.length; i++) {
  bytes[i] = i;
}

var more = new Buffer(4);
bytes.copy(more, 0.4.8); // bytes.length
more[0] / / 4
Copy the code
  • Buffer and string conversion

To convert a string to a Buffer object, you can use:

New Buffer(STR [,encoding]) — Creates a Buffer based on a string and encoding format. Utf8 is used by default if encoding is not specified.

Convert a Buffer object to a string:

The toString method converts the Buffer instance to a string in the specified encoding (utF8 by default).

var hello = new Buffer('Hello');
hello // <Buffer 48 65 6c 6c 6f>
hello.toString() // "Hello"
Copy the code
  • Buffer constructor
  1. new Buffer(size)To create a buffer of the specified size.
  2. new Buffer(array)To create a buffer from an array of bytes whose members must be integer values.
  3. new Buffer(str[,encoding]), creates a buffer based on a string and encoding format. If encoding is not specified, utF8 is used by default.
  4. new Buffer(buffer)Create a new buffer from the buffer instance.
  • Class method
  1. Buffer.isEncoding('utf8')Checks whether it is a valid encoding parameter. That is, check whether UTF8 is valid.
  2. Buffer.isBuffer(Date)Check if it is a Buffer object.
  3. Buffer.byteLength('Hello', 'utf8')Returns the actual length of the string in bytes, default utf8.
  4. Buffer.concat() merges a group of Buffer objects into a single Buffer object.
  • Instance methods
  1. write()Write data. The first argument is what was written, the second argument (omitted) is the starting position (defaults to 0), and the third argument (omitted) is the encoding, which defaults to UTF8.
  2. slice()Returns a Buffer instance referenced from the original object at the specified location. Its two arguments are the start and end positions. The slice method creates a view of the original memory and returns a buffer that references the same memory.
  3. toString()Convert to a string.
  4. toJSON()Convert the Buffer instance to a JSON object.

System module

System built-in, require() introduction, but do not need to download separately.

path

Path: Tool for handling file paths and directory paths.

Here are some uses of the methods provided by PATH:

let path=require('path');

// Get the directory path
let dir= path.dirname("/node/a/b/c/1.jpg");
/ / file name
let filename = path.basename("/node/a/b/c/1.jpg");
/ / suffix
let extname = path.extname("/node/a/b/c/1.jpg");

console.log(dir);
console.log(filename);
console.log(extname);

// resolve resolves a path with multiple parameters
console.log(path.resolve("/node/a/b/c/d".".. /"."e/f/g".".. /.. /"."h"));
Copy the code

Run output:

$ node test.js
/node/a/b/c
1.jpg
.jpg
e:\node\a\b\c\e\h
Copy the code

fs

Fs: used for file read and write operations.

The following is an example of using FS to read files, overwrite files, append files, and synchronize read and write files:

let fs=require("fs");

// Read a file
fs.readFile("./a.txt".(err,data) = >{
    if (err) {
        console.log(err);
    }
    else{
        
      
        //console.log(data);
        console.log(data.toString()); }})// Write to a file. If the file does not exist, it will be created. If it does, it will be overwritten
fs.writeFile("b.txt"."Hello, this is using Node to write a file (overwrite)".err= >{
    console.log(err);
})

// {flag:"a"} append to a file
fs.writeFile("b.txt"."Hello, this is using Node to write a file (append)", {flag:"a"}, err= > {
    console.log(err);
})

// Append to a file method
// fs.appendFile(filename,data,[options],callback);
fs.appendFile("b.txt".'Hello, this is using Node to write a file (append)'.function () {
    console.log('Append content done');
});

// Read synchronously
let fileContent=fs.readFileSync("a.txt");
console.log(fileContent.toString());

/ / write synchronization
let write=fs.writeFileSync("b.text"."Synchronous write file method");
console.log(write);
Copy the code

Custom modules

Nodejs supports custom modules, while using require you can introduce your own wrapped modules. And the introduction and use of third-party modules installed through NPM.

Module export:

  • exportsExports are an object through which a variable or parameter can be exposed.

For example, in a js file:

exports.a=1;
exposts.b="Hello, Node!";
Copy the code

To import and print variables in another file:

/* Introduce custom modules */
let importData=require("./exportsUse");
console.log(importData.a);
console.log(importData.b);
Copy the code
  • moduleExport, throughmodule.exportsYou can export variables, objects, functions, and so on.
module.exports=class{
    constructor(name){
        this.name=name;
    }
    holle(){
        console.log("Hello."+this.name); }}Copy the code

The introduction of

let mod = require("./exportsUse");
var m=new mod("Zhang");
m.holle();
Copy the code

Introduced the require

The use introduced by require has been demonstrated above. This paper mainly introduces the attention points of introduction.

When importing a custom module: you must use./ to specify the current path of the module, that is, you must specify the path of the module.

Otherwise, an error Cannot find Module is reported.

Not specifying a path will look up modules from the node_modules path.

Path lookup when require is introduced

  1. The default is node_modules in the current path.
  2. If not, look for the node installation directory.
  3. For modules of other paths, the path of the module must be specified, otherwise it cannot be found.

The HTTP module

The HTTP module is a system module provided by Node for creating Web services. You can easily enable a Web server to handle HTTP requests.

HTTP module usage

  • Create a server object:http.createServer()

Create a web server in httpser.js and listen on port 8080:

let http=require("http");

http.createServer((req,res) = >{
    console.log("This is the Web Server created by Node.");// Prints at the server terminal

    res.write("hello,i'm a Web Server!");
    res.end();
}).listen(8080);
Copy the code

The node to run:

$node httpServer This is the Web Server created by NodeCopy the code

Access the local port 8080: http://localhost:8080. The following information is displayed:

The HTTP Web Server returns the page on request

Create a Node server and return the file based on the requested URL.

let http=require("http");
let fs=require("fs");

http.createServer((req,res) = >{
    fs.readFile(`. /${req.url}`.(err,data) = >{
        if (err) {
            res.writeHead(404);
            res.end("404 Not Found");
        }else{
            res.end(data);
        }
    })

}).listen(8080);
console.log('Web service started, visit http://localhost:8080 to test ');
Copy the code

Start httpServer.js in the command:

The $node httpServer.js Web service is started. Visit http://localhost:8080 to testCopy the code

When requested to the path of an existing file, the contents of the file are returned:

1. HTML is a newly created HTML file in the same directory as httpServer.js.

In other cases, a 404 prompt is returned:

Data interaction for HTTP services

The following handling of web requests is based on the createServer callback in the httpser.js file above.

The GET method

Through the URL module, the url query string and routing information in get request are processed.

let fs=require("fs");
let url=require("url");

// Outputs the url of the parsed request
console.log(url.parse(req.url));

/* Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '? username=zhangsan&password=123456', query: 'username=zhangsan&password=123456', pathname: '/login', path: '/login? username=zhangsan&password=123456', href: '/login? username=zhangsan&password=123456' } */

// Format the query string when parsing the URL, and the query is formatted as a JSON object
console.log(url.parse(req.url,true));
/* Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '? username=zhangsan&password=123456', query: [Object: null prototype] { username: 'zhangsan', password: '123456' }, pathname: '/login', path: '/login? username=zhangsan&password=123456', href: '/login? username=zhangsan&password=123456' } */

// Get the request route and query string objects
let {pathname,query}=url.parse(req.url,true);
    console.log(pathname,query);
/* result /login [Object: null prototype] {username: 'zhangsan', password: '123456'} */
Copy the code

POST method

The POST method puts the requested data in the body of the request, so it can transfer large data (<2G, sometimes 1G).

Therefore, in the actual transmission of POST, data is transmitted to the Server segment by segment. In this way, the Node Server can accept each segment of data and finally combine it into the complete data to be sent.

req.on(“data”,(data)=>{… }) method, can accept each section of data transmission; req.on(“end”,()=>{… }) method, which is executed after the data is received.

let http=require("http");
let querystring=require("querystring");

let result=[];
// Receive the buffer of each segment
req.on("data".buffer= >{
    result.push(buffer);
})
// The data is processed
req.on("end".() = >{
    let data=Buffer.concat(result);
    console.log(data);
    console.log(data.toString());
    console.log(querystring.parse(data.toString()));
})
/* 
      
        username=zhangsan&password=123456 */
      
Parse [Object: null prototype] {username: 'zhangsan', password: '123456'} */
Copy the code

reference

Introduce the directory structure and order of the main reference basis from the front end of the interview points the Gospel – the node (content some old, but the introduction of process and thinking structure or great), the Buffer object, as well as the reference for the other information on the net, in addition to the given reference links, no longer list, all content is combined with actual example.

Download this sample source code