This chapter is mainly to expand the knowledge of the first chapter. It will be relatively boring. It is provided to students who have a better foundation or want to further study.

If some of these concepts and usages are not immediately clear, we will continue to look back at them with some experience with Nodejs and improve our own understanding

[TOC]

I. Module path resolution rules

  1. **require supports absolute paths starting with (/) or drive letter (C:)

  2. ** Relative paths: ** Supports relative paths starting with (./)

    == Note: == However, these two paths establish a strong coupling relationship between modules. Once the storage location of a module file needs to be changed, the code of other modules using this module also needs to be adjusted to become a whole body, so it is not recommended to use them.

  3. ** Third form of path (common method) : ** Written like foo/bar, parsed according to the following rules until a module is found

    • ** If you pass the NodeJS built-in module name to the require function, do not do path resolution and return the exported object of the internal module, such as require(‘fs’).

    • Node_modules directory: NodeJS defines a special node_modules directory for storing modules. For example, when a module whose absolute path is /home/user/hello.js is loaded with require(‘foo/bar’), NodeJS tries to use the following paths in sequence

      • /home/user/node_modules/foo/bar
      • /home/node_modules/foo/bar
      • /node_modules/foo/bar
    • **NODE_PATH environment variable: ** Similar to the PATH environment variable, NodeJS allows you to specify additional module search paths via the NODE_PATH environment variable. The NODE_PATH environment variable contains one to more directory paths, which are used on Linux: separated, used on Windows; Space. For example, the following NODE_PATH environment variable is defined:

      • NODE_PATH=/home/user/lib:/home/lib

      When a module is loaded using require(‘foo/bar’), NodeJS tries the following paths in turn.

      • /home/user/lib/foo/bar
      • /home/lib/foo/bar

2. Package concept

The basic unit of A JS module is a single JS file, but more complex modules are often composed of multiple sub-modules. For ease of management and use, we can call a large module consisting of multiple submodules a package and put all the submodules in the same directory.

Among all the submodules that make up a package, there needs to be an entry module whose export objects are used as the export objects of the package. For example, there is the following directory structure.

Where CAT defines a package containing three submodules, with main as the module entry file

// main.js

var head = require('./head');
var body = require('./body');

exports.create = function (name) {
    return {
        name: name,
        head: head.create(),
        body: body.create()
    };
};
Copy the code

Typically, you can get the entry file using the path: require(‘/home/lib/cat/main’), but to make the package look more like a separate module, you can do the following:

Js: ** When the entry file name is index.js, the module can be loaded with the directory of the module instead of the module file path, so the following two statements are equivalent.

  • require(“/home/lib/cat”)
  • require(“/home/lib/cat/index”)

After doing this, you just pass the package directory path to the require function, and it feels like the entire directory is being used as a single module, giving it a more holistic feel.

** Package. json: ** If you want to customize the name and location of the entry module, you need to include a package.json file in the package directory and specify the path of the entry module. The CAT module in the above example can be refactored as follows.

The content of package.json file is as follows

{
    "name": "cat"."main": "./lib/main.js"
}
Copy the code

In this way, the module can also be loaded using require(‘/home/lib/cat’). NodeJS will locate the entry module based on package.json in the package directory.

Iii. Project Catalog

- / home/user/workspace/node - echo / # # project directory - bin/store command line code node - echo + doc / # # documentation - lib/storage API code echo. Js - Node_modules/argv/ + tests/Copy the code

The contents of some files are as follows

/* bin/node-echo */
var argv = require('argv'),
    echo = require('.. /lib/echo');
console.log(echo(argv.join(' ')));

/* lib/echo.js */
module.exports = function (message) {
    return message;
};

/* package.json */
{
    "name": "node-echo"."main": "./lib/echo.js"
}
Copy the code

The above example stores different types of files and loads the module directly using the tripartite package name through the node_moudles directory. In addition, after package.json is defined, the Node-echo directory can also be used as a package.

Four NPM.

NPM is a package management tool installed with NodeJS, which can solve many problems in nodeJS code deployment. The common usage scenarios are as follows:

  • Allows users toNPMThe server downloads third-party packages written by others and uses them locally.
  • Allows users toNPMThe server downloads and installs command line programs written by others for local use.
  • Allows users to upload their own packages or command-line programsNPMThe server is used by others.

4.1 Downloading third-party Packages

Search for the package to be downloaded on the NPM official website and run the following command to download the package

NPM install Package name NPM install package name @Specify versionCopy the code

By default, the package of the latest version is downloaded. To download the package of the specified version, add @ to specify version after the package name

If a large number of third-party packages need to be downloaded, you can specify dependencies and versions in package.json configuration and run the NPM install command in the project directory to download and install them in batches

More importantly, after the project is uploaded to the NPM server, other people download the project, and the dependency files of the project will be automatically added

{
    "name": "node-echo"."main": "./lib/echo.js"."dependencies": {
        "argv": "Hundreds"}}Copy the code

4.2 Installing the CLI

Downloading and installing a command line program from the NPM service is similar to a three-way package.

  • NPM install Install package name -g

4.3 Publishing Code

You need to register an account before publishing code with NPM for the first time. Run NPM adduser on the terminal and follow the instructions. With the account done, we then need to edit the package.json file to add the required fields for NPM.

{"name": "node-echo", "node-echo", "node-echo", "node-echo" "Hundreds"}, "main" : ". / lib/echo. Js ", # entry module position "bin" : {" node - echo ":". / bin/node - echo "# command line program name and position of the main module}}Copy the code

After that, we can run the NPM publish publish code in the package.json directory.

4.4 the version number

When you download and distribute code using NPM, you are exposed to the version number. NPM uses semantic version numbers to manage code, which are briefly described here.

The semantic version number is X.Y.Z, representing the major version number, minor version number, and patch version number respectively. When code changes, the version number is updated according to the following principles.

+ If it is just a bug fix, you need to update the Z bit. + If it is a new function, but backward compatibility, need to update the Y bit. + If there is a big change, the X bit needs to be updated for downward incompatibility.Copy the code

Version numbers With this guarantee, you can rely on a range of version numbers in addition to a fixed version number when claiming third-party package dependencies. For example, “argv”: “0.0.x” depends on argv, the latest version of the 0.0.x series. All version number ranges supported by NPM can be viewed in official documentation.

4.5 Extension of NPM usage

NPM provides a lot of functionality beyond what is covered in this chapter, and there are many other useful fields in package.json. In addition to the official documentation available at npmjs.org/doc/, here are some common NPM commands.

  • NPM provides many commands, such asinstallandpublish, the use ofnpm helpYou can view all commands.
  • usenpm help <command>You can view the detailed help information about a command, for examplenpm help install.
  • inpackage.jsonUse it in the directory where it is locatednpm install . -gYou can install the current command line program locally and use it for local testing before publishing.
  • usenpm update <package>Can put the current directorynode_modulesThe corresponding module in the subdirectory is updated to the latest version.
  • usenpm update <package> -gYou can update the corresponding command line program of the global installation to the latest version.
  • usenpm cache clearYou can clear the NPM local cache for anyone who releases a new version of code with the same version number.
  • usenpm unpublish <package>@<version>You can cancel the release of a version of your code.

5. Summary

This chapter describes the preparation you need to do before writing code using NodeJS. It summarizes the following points:

  • Plan out the directory structure before writing code to keep things organized.
  • Larger programs can split code into modules to manage, and larger programs can use packages to organize modules.
  • The rational use ofnode_modulesandNODE_PATHTo decouple the package usage from the physical path.
  • Use NPM to join the NodeJS ecosystem.
  • Please register on NPM in advance when you think of a desired package name.