Home >Web Front-end >JS Tutorial >Introduction to the Node.js module system and how to load modules

Introduction to the Node.js module system and how to load modules

不言
不言Original
2018-08-23 17:36:501612browse

This article brings you an introduction to the Node.js module system and how to load modules. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1.Node’s module system

In the Node.js module system, each file is an independent module;

Each module will have its own scope;

// var 声明的全局变量 等同于 全局对象的属性
//     username不是全局变量,在模块作用域中
var username =  "Jack";
 
console.log(username);
// console.log(window.username);//输出报错

2. Loading the module

(1) Core module

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

(2) Third-party module

Command line download third-party module:

For example, random number

npm install randomatic

Quote :

const randomtic = require("randomatic");
console.log(randomtic("*",20));

(3) Custom module

//自定义模块
// 新建js文件
const aModule = require("./独立模块.js");
console.log(aModule.a);

Independent module.js

//每个独立的文件都是模块,有自己的作用域
console.log("我是独立模块");
 var a =100;//主模块不能直接调用,所以往往通过exports实现
exports .a = a;

Note: The custom module require will determine whether there is "./"" in front of the module name. ../ " " / ",

Add before the custom module: " ./ " " ../ " " / ";

If there is no customization, it will be the core and location. For third-party modules, core modules are loaded first;

Related recommendations:

Introduction to the content in Node.js custom modules (with code)

Introduction to the content of module paths in Node.js

The above is the detailed content of Introduction to the Node.js module system and how to load modules. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn