This goal

  • Build the Node running environment
  • Master the running method of NodeJS program
  • Understand modular development
  • Understand system modules and third-party modules
  • Understand the package.json file

1. Overview of Node development

1.1 Why learn server-side development

Why do front-end people learn server-side development?

  • Be able to work more closely with back-end programmers
  • Website business logic in front, learning front-end technology needs back-end technology support (Ajax)
  • Broaden your knowledge horizon and look at the whole project from a higher perspective

1.2 What does server-side development do

  • Realize website salesman logic
  • Add, delete, change and check data

1.3 Why choose Node as the server technology

  • Develop back-end technologies using familiar JS syntax
  • Many companies in first-tier cities
  • The ecosystem is active and there are plenty of open source libraries available
  • Front-end development tools are mostly developed based on Node

1.4 what Node is

The Node’s official website

The Node Chinese website

Node.js is a JavaScript runtime (runtime environment) based on Chrome V8 engine. For example, the browser is also the JS runtime environment, and Node is also the JS runtime environment, but the APPLICATION scenario of JS code is extended to the server side

2. Set up the Node running environment

2.1 installation

Go to the Node official website

If it’s not the version you want, click the ‘DOWNLOADS’ link on the page to go to the download page

Once the download is complete, double-click setup

The following shows the installation process in screenshots. The default installation directory can be used. Note that the installation directory cannot be In Chinese

The installation process

Note: once installed, there are no shortcuts on the desktop, because Node is just a JS execution environment

Using Node requires command-line tools

How do I test whether Node is installed successfully?

Open the command line tool, here can use the traditional CMD tool, also can use the Powershell in Win10

We use the latter here

Press the Windows +S key on the keyboard and type Powershell to search for PowerShell tools

Or anywhere, such as the desktop, holding down the Shift key along with the right mouse button will also bring up powerShell tools

On the cli, run the following command

node -v
Copy the code

If the version number is displayed, Node is successfully installed

2.2 Solution to Environment Installation Failure

2.2.1 Error code 2502/2503

Indicates that the current user has insufficient permissions.

Solutions:

  • Run powerShell tools as an administrator
  • It belongs to the command to run the installation package: msiexec /package Node installation package location, if my installation package is in the following location

Then run the following command to install the software

2.2.2 Environment Variables

When you type node -v in Powershell, you will get an error message indicating that Node is not a recognized command because the node executable path has not been added to the environment variable

The method of adding environment variables is not demonstrated here

3. Introduction to the Node

3.1 the Node. Js

  • JavaScript consists of three parts: ECMAScript, DOM, and BOM
  • Node.js is made up of additional apis provided by ECMAScript and the Node environment, including files, networks, paths, and more powerful apis

3.2 Basic syntax and operation

First, all of the previously learned ECMAScript syntax is available in Node, including ES6 syntax

3.2.1 Running the Node program

So how do we execute our JS code in the Node environment?

We begin writing and executing our first Node program by following these steps

  • Open any development tool you’re familiar with, such as Sublime, VS Code, or Notepad

  • Create a new file called hello.js. Note that the file name extension is.js, not.html

  • Write the following test code

    let ary = [12.3.4.5]
    ary.forEach(item= > console.log(item))
    Copy the code
  • Find the location of the Hello.js file, then hold down the Shift key to right click and select “Open PowerShell window here”

  • Enter the following command on the CLI

node hello.js 
Copy the code

After hitting enter, you can execute the code in Hello.js

3.2.2 summary

Through the above code writing and execution, we summarize the following points

  • Nodefiles have.js extensions
  • In the previous study, js files are introduced into HTML to execute JS code in the way of running HTML files, but Node is a server technology. In node technology, there is no DOM and BOM, so the operation mode is different from before
  • The node program is run using the Node command with the file name
  • In addition to running Node programs from the command line, many development tools, such as VS Code, can also run Node programs

3.3 global

As we learned earlier, Console is the global object of the Window, but in Node, global is the global object

Node has the following methods under global objects, which can be used anywhere. Global can be omitted

  • Console.log () is printed in the console
  • SetTimeout () Sets the timeout timer
  • ClearTimeout () Clears the timeout timer
  • SetInterval () sets the interval timer
  • ClearInterval () Clears the intermittent timer

Create a new global.js file and write the following generation

global.setTimeout(() => {
    console.log('timeout')
}, 2000);
Copy the code

Run the global.js file to test

Prove that these apis are indeed in the global object global

4. Modular development

4.1 Existing disadvantages

In our short js code writing experience, we may or may not realize that JS development has the following disadvantages

  • File dependencies: File dependencies are not clear and need to be analyzed manually
  • Name conflict: Two JS files may have variables or files with the same name, which may cause the later file to overwrite the earlier file

For example:

4.2 Modularization development in software

A function is a module, multiple modules can form a complete application, the removal of a module will not affect the operation of other functions

Modularity development specification in 4.3 Node

So how do you do modular development?

  • Node.js specifies that a JavaScript file is a module, and variables and functions defined inside the module are not available externally by default
  • Members can be exported from within a module using the Exports object and imported from other modules using the require method.

Note: This is just the modular development specification for Node; ES6 has its own modular development specification

Code demo:

Create a new M.js and write the following code

Var sum=(a,b)=>a+b exports. Name =name of exportsCopy the code

Create a new n.js and write the following code

Const m = the require ('. / modes s) console. The log (m. d) console. The log (Margaret spellings s (4, 5))Copy the code

Run n.js and you can see the result

Small make up to reassure

Note the following points

  • When m.js is introduced in n.js, the following.js can be omitted
  • When introducing m.js, use the following “./m.js”
  • In M. exports, the property name after exports can be any name

Comparison of two module member export methods in 4.4 Node

exports.name=name
module.exports.name=name
Copy the code

The above example uses exports. attribute = attribute value to export module members

Module members can also be exported using module.exports. property = property value

Conclusion:

Exports is an alias (address reference relationship) of module.exports

So let’s prove this

For example, write the following code in M.js

Name =name module. Exports. Age =ageCopy the code

Write the following code in N.js

const m=require('./m.js')
console.log(m)
Copy the code

The output

{name: 'li Bai ', age: 20}Copy the code

Exports, module. Exports and module. Exports are the same address

Modify m.JS again

Let name=' name 'let age=20 module.exports. Name =age exports. Name =nameCopy the code

Run n.JS again

{name: 'li Bai'}Copy the code

Exports and module.exports set the name attribute, but one set the value to age and the other to name. Module. exports is the same

This proves the above conclusion

5. System module

5.1 What is a System Module

The API provided by the Node runtime environment. Because these apis are developed in a modular manner, we also call the API provided by the Node runtime environment system modules

Small make up to reassure

In the previous section, we learned a lot about JS apis, such as querySelector, getElementById, offsetLeft, etc. These are all Dom or Bom related functions provided by browsers, but these apis are scattered without any relationship.

Node also provides many apis, but these apis are stored in different modules depending on the severity. For example, the file module contains many apis that can manipulate disk files

Therefore, we can sum up as follows:

  • Modularity is the partitioning of related apis into different files by type
  • A system module is a set of apis that Node has defined in advance
  • In addition to system modules, developers can also develop third-party modules, which can be used by other developers. For example, m.js is also a third-party module

Here are a few system modules to understand the basic rules of code writing in Node, and how modules are introduced and used

5.2 File Operations

Node.js Chinese manual

5.2.1 Reading Files

Grammar:

fs.readFile(path[, options], callback)
Copy the code

Look at the case

const fs=require('fs')
fs.readFile('m.js','utf8',(err,data)=>{
    console.log(err)
    console.log(data)
})
Copy the code

Small make up to reassure

  • System modules are also introduced using require
  • Module names are enclosed in quotes
  • ReadFile is an asynchronous method, so the callback function needs to receive the read results
  • In the callback function, err gets an error message from the read. If no error occurred during the read, the result is null. Data indicates the content of the file read

Therefore, the value of Err is usually checked before processing the read file

const fs = require('fs')
fs.readFile('m1.js'.'utf8'.(err, data) = > {
    if (err) throw err;
    console.log(data)
})
Copy the code

5.2.2 Writing files

grammar

fs.writeFile(file, data[, options], callback)
Copy the code

case

Const fs = require('fs') fs.writefile ('./demo.txt', 'err ', err => {if (err) throw err; Console. log(' file was written successfully ')})Copy the code

Small make up to reassure

  • The callback function has only one parameter, err

5.3 Path Operations

5.3.1 Path Stitching

grammar

path.join([...paths])
Copy the code

Concatenate all the given path fragments together using platform-specific delimiters as delimiters, and then normalize the generated path.

Small make up to reassure

Because path separators are not uniform across different platforms, path concatenation is needed to prevent path separators from being written to death and affecting the cross-platform characteristics of programs

case

const path=require('path')
let res=path.join('public'.'static'.'images'.'time.jpg')
console.log(res)
Copy the code

Windows platform running results

public\static\images\time.jpg
Copy the code

Linux platform running results

public/static/images/time.jpg
Copy the code

5.3.2 Relative Path or Absolute Path

  • Absolute paths are used in most cases, because relative paths are sometimes relative to the current working directory of the command line tool
  • When reading a file or setting the file path, the absolute path is selected
  • Use __dirname to get the absolute path to the current file

Code demo:

Create a new file, write some code

const fs=require('fs')
fs.readFile('m.js'.'utf8'.(err,data) = >{
    if(err) throw err
    console.log(data)
})	
Copy the code

In the directory where the file resides, open the command line tool and run the file

On the CLI, run the following command to go up to the level-1 directory

cd ..
Copy the code

Execute the command again

So we need to get the absolute path in our code, based on the file path we’re currently writing, and then concatenate the file path into an absolute path, and we’re good

Small make up to reassure

The command line tool directory is the directory where you open the command line tool

If you have command line tools open on your desktop, then directories are

If the command – letter tool is opened in the root directory of drive D, then the directory is

But when writing code, we really want to use the relative path based on the file we’re currently writing

6. Third-party modules

Modules written by others with specific functions that we can use directly are third-party modules, also known as packages because third-party modules are usually composed of multiple files and placed in a folder.

Third-party modules exist in two forms:

  • It exists in the form of JS files and provides THE API interface for realizing the specific functions of the project. This module is mostly installed locally
  • In the form of command line tools to assist project development, this module is mostly installed globally

6.1 How can I Obtain a Third-party Module

www.npmjs.com/

Developers will develop third-party modules, uploaded to the site, other developers can download from the site

The download mode is cli

Here is the basic syntax for downloading and uninstalling third-party modules

  • Download: NPM install module name
  • Uninstall: NPM unintall Package module name

According to the function of the module, it can be divided into global installation and local installation

  • Local installation: The module is downloaded to the command line tool directory and can only be used by the current project
  • Global installation: modules are downloaded from the global directory and are available to all projects

6.2 Installation Demo

6.2.1 Local Installation

npm install jquery
Copy the code

After the installation is complete, the node_modules directory is created in the current directory

uninstall

 npm uninstall jquery
Copy the code

6.2.2 Global Installation

Take the Nodemon module as an example

Nodemon is a command-line tool used to aid project development. In Node.js, you have to re-execute the file in the command line tool every time you modify it, which can be tedious.

The installation

npm install nodemon -g
Copy the code

uninstall

npm uninstall nodemon -g
Copy the code

6.2.3 What Can I Do If The Installation Is Slow

Because the nPMjs.com server is in a foreign country, the download is sometimes slow or always disconnected

The solution is to change the download source, preferably a domestic download source

There are two solutions

  • Install the NRM and use the NRM to change the download source. After the change, run the NPM command to install the module
  • Install the CNPM, and then use the CNPM to install the module
6.2.3.1 NRM

By installing NRM, you can select and switch download sources

Using the step

  • Use NPM install NRM -g to download it
  • Example Query the list of available download addresses NRM ls
  • Change the NPM download address. NRM use Download address name
  • NPM install Installs the module name

Small make up to reassure

In the mirror source, CNPM and Taobao are actually the same, so you can choose Either Taobao or CNPM

6.3.2.2 CNPM

In addition to switching the download address to CNPM, you can also install CNPM directly

Install CNPM using NPM, and change the download source to Taobao

npm install -g cnpm --registry=https://registry.npm.taobao.org
Copy the code

After the installation, run the CNPM command to install the third-party module, for example

 cnpm install jquery
Copy the code

Note: CNPM is just a small public exercise based on NPM

6.3 yarn

NPM is a node.js based package management tool. In addition, yarn is also very popular now

Yarn is a very popular package management tool based on Node.js. It is a two-horse race with NPM

Note: YARN is different from CNPM

6.3.1 yarn installation

Yarn installation

In addition to downloading the installation package, you can also install YARN from NPM

Install YARN using the NPM package (although yarn competes with NPM, NPM is still open to install yarn)

 npm install yarn -g
Copy the code

Run the following command to query the YARN command list

yarh -h
Copy the code

Querying the YARN Version

yarn -v
Copy the code

6.3.2 YARN Installation and Modules

Create a new project, then open the command line tool and execute the following command

yarn add jquery
Copy the code

Delete module

yarn remove jquery
Copy the code

Small make up to reassure

  • Do not use NPM and YARN for package management in a project
  • NPM and YARN capabilities, we only use 1/10,000 of them, more on that later

7. Package. The json file

7.1 Node_modules problem

We found that when installing a module using NPM, the node_modules directory is created, which stores the downloaded modules and their dependencies

There are two problems with the files in this directory

  • There are so many folders and files that the transfer speed is slow when copying the whole project to others (in fact, node_modules is the main size of the Node project).
  • Complex module dependencies need to be logged to ensure that the version of the module is the same as the current version, otherwise the current project will run with an error

7.2 Package. json Resolve the problem

When the project is copied to others, delete node_modules, and then use NMP command to restore the installation

This requires a file to record which modules are used in the current project, and that file is package.json

Create package. Json

By default, this file is not available and can be generated using commands

Create a new project, then open the command line tool under this item and run the following command

npm init -y
Copy the code

The package.json file contains the following contents

{" name ":" package_demo ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }Copy the code

Install the module

 npm install debug needle
Copy the code

Watch the package.json file change

Delete node_modules

To copy the project to someone else, simply delete the node_modules directory

Restore to install

Run the following command to resume the installation based on the records in package.json

npm install
Copy the code

7.3 Project dependency and development dependency

  • Project depend on
    • In the development stage and online operation stage of a project, it needs to rely on the third-party package, called project dependency
    • Files downloaded using the NPM install package name command are added to the Dependencies field of the package.json file by default
  • Development depends on
    • Development dependencies are third-party packages that need to be relied on during the development phase of a project but do not need to be relied on during the online operation phase
    • Use the NPM install package name –save-dev command to add the package to the devDependencies field of the package.json file

Case demonstration:

Use the following command to install the development dependencies: gulp

npm install gulp --save-dev
Copy the code

Check the package. The json

Delete the node_modules directory

Use the following command to restore the project dependent installation

 npm install --production
Copy the code

Check for file changes in node_modules

Remove node_modules again, and then use the following command to restore the development dependency installation

npm install
Copy the code

There are a lot of files in node_modules

8. package.lock.json

This file is created the first time a module is downloaded using NPM

Functions are as follows:

  • Lock the version of the package to ensure that the next download will not cause problems due to a different package version
  • Speed up the download, because the tree structure of the third-party packages the project depends on and the download address of the packages are already recorded in this file, and reinstallation requires no additional work to be downloaded

9. Module loading rules

9.1 Module has paths

There are two cases

Require ('./yhb') // owns the path but does not have the suffixCopy the code
  • The require method looks for a module based on its path, or if it’s a full path, imports the module directly
  • If the suffix of the module is omitted, look for the JS file with the same name first and then the JS folder with the same name
  • If you find a folder with the same name, look for index.js in the folder
  • If the folder does not have index.js, it will look for the entry file in the main option in the package.json file in the current folder
  • If the specified entry file does not exist or no entry file is specified, an error is reported and the module was not found

9.2 No Path

require('yhb')
Copy the code
  • Node.js assumes it is a system module
  • Node.js goes to the node_modules folder
  • First, see if there is a JS file with that name
  • See if there is a folder with that name
  • If it is a folder, see if there is index.js in it
  • If there is no index.js look at the main option in package.json in that folder to determine the module entry file
  • Otherwise, no error can be found

Small make up to reassure

If the module has no path, Node considers it a system module

If the module has a path, Node assumes it is a module file defined by the developer