Node. Js

The module management system in Node.js follows the CommonJS specification. Modules are an essential part of Node.js. A Node.js file is a module (which could be JavaScript code, JSON, compiled C/C++ extensions, etc.)

Node. Js module

When writing a relatively large program, the code is generally modularized to make the program easier to develop and maintain.

Node.js modules follow the CommonJS specification, and a single file is a module. Each module is a separate scope and provides two main functions:

  • Var path = require(‘path’)
  • Exports objects are exports of the current module and are used to export module public methods and properties. Exports is a reference to module.exports

Node.js itself implements the require method as its way of introducing modules, and NPM is based on the package specification defined by CommonJS

Example node.js module

// add.js
const add = (a, b) = >{
    return a+b
}

module.exports = add
Copy the code
// index.js
const add = require('./add')

let result = add(1.2)
console.log(result)
Copy the code

The module reference

The require() method accepts a module identifier to import the module

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

Importing a module in Node goes through three steps:

  • Path analysis
  • File location
  • Compile implementation

Node preferentially loads modules from the cache. Node modules fall into two categories:

  • The core modules provided by Node
  • User-written file modules

The Node core module is the second fastest to load from cache, followed by the path module, and the slowest is the custom module.

The module definition

In modules, the context provides methods or variables that export modules. It is the only exit, for example:

exports.add = function(){
  // TODO
}
Copy the code

There is also a Module object in the module, which represents the module itself and exports is its property. For convenience, Node provides an exports variable for each module, pointing to module.exports. This equates to a line of command in the header of each module

var exports = module.exports
Copy the code

You can’t point an exports variable directly to a value because that breaks the link between exports and module.exports

Exports and Module. exports

  • Exports is just an address reference to module.exports. Node.js will export only the reference to module.exports. If the reference to exports changes, exports will no longer refer to Module. exports and will not be exported.
  • Module. exports is a real interface, exports is just an accessory to it. Module. exports is returned to the call instead of exports.

All exports collected properties and methods are assigned to module.exports. Module. exports does not have any properties or methods. Exports :: tip Node developers recommend exporting objects using module.exports and exporting multiple methods and variables using exports :::

NPM module manager

NPM is designed to solve the installation and unloading of packages, dependency management, version management and other problems on the basis of CommonJS specification. NPM does not need to be installed separately. NPM is installed when installing Node. You can:

  • Download and install third-party packages written by others from the NPM server for local use.
  • Allows users to upload their own packages or command-line programs to the NPM server for others to use.

NPM package

A CommonJS compliant package should have the following structure:

  • Package. json, which typically resides in the top-level directory of an NPM package
  • Binary files, usually stored in the bin directory
  • JavaScript source code, usually in the lib directory
  • The documentation, 舤, is in the doc directory
  • Unit tests, usually in the test directory

package.json

  • Name: specifies the package name. It must be unique on the NPM. Lowercase letters and digits can contain underscores (_ -). But no Spaces
  • Description: Describes the NPM package.
  • Version: indicates the version number. A semantic version number (semver.org/), usually X.Y.Z. This version number is very important and is often used in some version control situations
  • Keywords: keyword group. For classification search in NPM
  • Maintainers: An array of package maintainers. The array element is a JSON object containing the name, email, and Web properties
  • 3. That’s an array of contributors. The first is the author of the bag himself. In the open source community, if a submitted patch is merged into the master branch, the person contributing the patch should be included. The format contains name and email
  • Bugs: A URL where bugs can be submitted. This can be an email address (mailto:mailxx@domain) or a web address
  • Licenses: license used by the package
  • Repositories: An array of addresses hosting the source code
  • Dependencies: Dependencies required by the current package. This property is so important that NPM automatically loads dependent packages for you

In addition to the mandatory fields mentioned earlier, there are additional fields such as bin, scripts, Engines, devDependencies, and Author

The use of NPM

Common NPM viewing commands are:

  • View the list of NPM commands:npm help
  • See the simple usage of each command:npm -l
  • View the version of NPM:npm -v
  • View the configuration of NPM:npm config list -l

Common NPM package commands

The Node module is installed using the NPM install command.

Each module can be “globally installed” or “locally installed”.

  • Global installation is the installation of a module into the system directory, each project can be called. In general, global installation applies only to tool modules.
  • To install locally, you download a module to the node_modules subdirectory of the current project, and then call the module only from within the project directory.

Local installation:npm install <package name>

Global installation:

sudo npm install --global <package name>

or

sudo npm install -g <package name>

A dependency that specifies the nature to which the installed module belongs

  • – -save: The module name is added to dependencies, which can be simplified as the -s parameter.
  • — -save-dev: the module name is added to devDependencies, which can be simplified to the -d argument.
npm install <package name> --save
npm install <package name> --save-dev
Copy the code

Uninstalling modules:npm uninstall <package name>

Update module:npm update <package name>

Create a module:npm init

The NPM init creation module will help us produce package.json files on the interactive command line

E:\github\coding_docs>npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. Package Name: (coding) Demo version: (1.0.0) Entry point: (index.js) Keywords: just a demo npm package license: (MIT) About to write to E:\github\coding_docs\package.json: { "name": "Demo", "version" : "1.0.0", "main" : "index. Js", "scripts" : {" dev ":" vuepress dev docs ", "build" : "vuepress build docs", "deploy": "yarn build && ./deploy.bat" }, "repository": { "type": "git", "url": "git+https://github.com/hijameszhang/coding.git" }, "author": "jameszhang <[email protected]>", "license": < span style = "box-sizing: border-box; color: RGB (0, 0, 0); line-height: 21px; font-size: 14px! Important; word-break: inherit! Important;" "./node_modules/cz-conventional-changelog" } }, "description": "Record some of the experience accumulated during the coding process", "bugs": { "url": "https://github.com/hijameszhang/coding/issues" }, "homepage": "https://github.com/hijameszhang/coding#readme", "directories": { "doc": "docs" }, "dependencies": {}, "keywords": [ "just", "a", "demo", "npm", "package" ] } Is this OK? (yes) yes E:\github\coding_docs>Copy the code

Enter the above information according to the actual situation. Generally, press Enter by default. Finally, a package.json file is generated in the current directory.

Module to release

Before publishing a module, you must first register users with NPM

Register a new NPM user

E:\github\coding_docs>npm adduser
Username: jameszhang
Password:
Email: (this IS public) [email protected]
E:\github\coding_docs>npm publish
Copy the code

Now our NPM package has been successfully released.

A link to the

NPM document