Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-08-23 17:36:50
Original
1584 people have browsed it

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);//输出报错
Copy after login

2. Loading the module

(1) Core module

let http = require("http");
let fs = require("fs");
Copy after login

(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));
Copy after login

(3) Custom module

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

Independent module.js

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!