1. Node.js modular development

1.1 Disadvantages of JavaScript development

There are two major problems with JavaScript: file dependencies and naming conflicts.

1.3 Modular 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

1.4 Modular development specifications in Node.js

  • 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.

1.5 Exporting Module members

// let version = 1.0; // Define method const satHi = name => 'Hello, ${name}'; // Export data exports.version = version; exports.sayHi = sayHi;Copy the code

1.6 Importing module members

// let a = require('./b.js'); // Output the version variable console.log(a.sion) in module B; // Call the sayHi method in module B and print its return value console.log(a.sayhi (' dark horse zombie '));Copy the code

You can omit the suffix when importing modules

1.7 Another way to export module members

module.exports.version = version;
modele.exports.sayHi = sayHi;
Copy the code

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

1.8 The connection and difference between the two modes of module export

3. System module

3.1 What is a system module

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

3.2 System Module FS File Operation

F :file, s:system, file operating system.

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

Reading file contents

Fs.reaflie (' file path/file name '[,' file code '], callback);Copy the code

Sample syntax for reading files

const fs = require('fs'); // Read base.css fs.readfile ('.. /css/base.css','utf-8'(err, If (err == null) {console.log(doc); if (err == null) {console.log(doc); }});Copy the code

Write file contents

Fs. writeFlie(' file path/file name ',' data ', callback);Copy the code
const fs = require('fs'); Const content = '<h3> writing file contents with fs.writeFile </h3>'; first.writeFile('.. /index.html', content, err => { if (err ! = null) { console.log(err); return; } console.log(' file was written successfully '); });Copy the code

3.3 System Module Path Path operation

Why do path concatenation

  • The path delimiters vary with operating systems
  • /public/upload/avatar
  • On Windows, it’s \ /
  • On Linux is /

3.4 Syntax for Path Stitching

Path.join (' path ',' path ',...)Copy the code
// import path module const path = require('path'); / / path joining together let finialPath = path. Join (' itcast ', 'a', 'b', 'Arthur c. ss'); Itcast \a\b\c.css console.log(finialPath);Copy the code

3.5 Relative path VS Absolute Path

Use the relative path or absolute path, depending on whether the relative path corresponds to the current file.

  • Absolute paths are used in most cases, because relative paths are sometimes relative to the current working directory of the command line tool (using path.join)
  • 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

4. Third-party modules

4.1 What is a third-party module

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 API interfaces for realizing specific functions of the project
  • It exists in the form of a command line tool to assist in project development

4.2 Obtaining third-party Modules

Npmjs.com: Repository for storage and distribution of third-party modules

Node Package Manager (NPM): a third-party node module management tool

  • Download: NPM install module name
  • Uninstall: NPM uninstall Package Module name

Global installation vs. local installation

  • Command line tools: Global installation
  • Library files: locally installed

4.3 The Third-party Module Nodemon

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.

Using the step

  1. Use NPM install nodemon-g to download it (-g is installed globally and can be used by any project)
  2. Replace the Node command execution file with the Nodemon command in the command line tool (CTRL + C stop)

4.4 Third-party Module NRM

NRM: NPM download address switching Tool The default NPM download address is in a foreign country, but the download speed is slow in China

Using the step

  1. Use NPM install NRM -g to download
  2. Query the list of available download addresses NRM ls
  3. Change the NPM download address. NRM use Download address name

4.5 Third-party Module Gulp

Front-end construction tool based on node platform development

Write mechanized operations as tasks, and when you want to perform mechanized operations, execute a command line command and the task is automatically executed

Use machines instead of handwork to improve development efficiency.

4.6 What can Gulp do

  • Project online, HTML, CSS, JS file compression merge
  • Syntax conversion (ES6, less…)
  • Public files are removed
  • Modify the file browser automatically refreshes

4.7 Gulp use

  1. Run the NPM install gulp command to download the gulp library file
  2. Create the gulpfile.js file in the project root directory
  3. The SRC directory houses the source files. The dist directory houses the post-build files
  4. Write tasks in the gulpfile.js file
  5. Execute the gulp task in the command line tool

4.8 Methods provided in Gulp

  • Gulp.src (): Gets the file to be processed by the task
  • Gulp.dest (): Output file
  • Gilp.task (): Creates a GULp task
  • Gulp.task (): Creates a gulp task
  • Gulp.watch (): Monitors file changes
const gulp = require('gulp'); // Use gulp.task() to create task gulp.task('first', () = > {/ / get to deal with file gulp. SRC ('. / SRC/CSS/base. CSS ') / / will process after the file output to dist directory. The pipe (gulp. Dest ('/dist/CSS ')); });Copy the code

4.9 Gulp plug-in

  • Gulp-htmlmin: HTML file compression
  • Gulp – csso: compress CSS
  • Gulp-babel :JavaScript syntax conversion
  • Gulp-less: syntax transformation of less
  • Gulp-uglify: Compression obfuscates JavaScript
  • Gulp-file-include Includes public files
  • Browsersync browser synchronizes in real time

The following errors often occur when using anonymous functions when executing tasks using Gulp4.0

3. Return a callback

This is the simplest method, and gulp automatically returns the callback function as an argument to the task, which must be called upon completion. As follows:

gulp.task(‘default’, gulp.series(‘server’, (done) => done()))

Task function must be specified

The solution

Instead of using Gulp3 to specify dependent tasks, you need to use gulp.series and gulp.parallel because gulp tasks now only have two parameters.

  • Gulp.series: Execute in order
  • Gulp. Paralle: enables parallel computation
gulp.task('my-tasks', gulp.series('a', 'b', 'c', function() {
  // Do something after a, b, and c are finished.
}));
Copy the code
gulp.task('build', gulp.parallel('styles', 'scripts', 'images', function () {
  // Build the website.
}));
Copy the code

Or it

gulp.task('my-tasks', gulp.series('a', gulp.parallel('styles','scripts', 'images'), 'b', 'c', function() {
  // Do something after a, b, and c are finished.
Copy the code

The related task must occur before it is invoked.

6. Package. The json file

6.1 Node_modules folder problems

  1. Too many folders and files are too fragmented, and when we copy the whole project to others, the transmission speed will be very slow
  2. 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

6.2 Functions of package.json Files

Project description file, which records the current project information, such as project name, version, author, Github address, which third party modules the current project depends on, etc. Run the NPM init -y command.

6.3 Project Dependency

  • In the development speed node and online operation stage of a project, it needs to rely on the third-party package, which is called project dependency
  • Files downloaded using the NPM install package name command are added to the dependcides field of the package.json file by default
Remote running, remote running, remote running, remote running, remote running, remote running, remote runningCopy the code

6.4 Development Dependencies

  • Dependency is required in the project development stage, but not in the online operation stage, which is called development dependency
  • Use the NPM install package name –save–dev command to add the package to the devDependencise field of the package.json file

6.5 Function of package-lock.json file

  • 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

5. Node.js

5.1 Module Lookup Rule – when a module has a path but no suffix

require('./find.js);
require('./find);

Copy the code
  1. The require method looks for a module based on its path, or if it’s a full path, imports the module directly
  2. 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
  3. If you find a folder with the same name, look for index.js in the folder
  4. If there is no index.js in the folder, it will look for the entry file in the main option in the package.js file in the current folder
  5. An error is reported if the specified entry file does not exist or if no entry file is specified, the module was not found

5.2 Module Lookup Rule – When a module has no path and no suffix

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