1. Start
node.js:https://nodejs.org
2.Moudle
JS programming, because you can write code directly in the global scope, so that developers can easily create a new global variable or this global module, these global variables or global modules in the development of engineering, it is very easy to conflict with each other, but also difficult to understand the interdependence between them. node. JS uses the COMMONJS specification to define modules and use modules, providing required and module.exports to solve this problem.
The required () method, which references other modules to the current scope through the required method.
The Module.exports method, which exports objects from the current scope, object or class to define the function.
Define a module that contains only static methods
circle.js: Two methods are available
Area (), circumference () to find the perimeter
Const PI = Math.pi;exports.area = (r) = = Pi * r * r;exports.circumference = (r) = 2 * PI * r;
Call this module app.js :
Const CIRCLE = require ('./circle.js '); Console.log (' The area of a circle of radius 4 is ${circle.area (4)} ');
The example code above defines a module=. NET contains static classes for static methods.
Defines a module that represents the normal class
User.js: Defining a User class
' Use strict '; const UTIL = require (' util '); function User (sId, sName) {this . Id = sId; This. Name = SName; ncount++;} User.prototype.toString = function () { return Util.format ("id= '%s ', name= '%s '", this.) Id, this. Name);} Module.exports = User;
App.js:
var user = require ('./user '), var psource = [];p source.push (new User (' Liubei ', ' Liu Bei '));p source.push (' Guanyu ', ' Guan Yu ');p Source.push (New User (' Zhangfei ', ' Zhang Fei ')); for (var index = 0; index < psource.length; index++) { var element = PS Ource[index]; Console.log (' ${element.tostring ()} ');}
Console
Id= ' Liubei ', Name= ' Liu Bei ' id= ' Guanyu ', name= ' Guan Yu ' id= ' Zhangfei ', Name= ' Zhang Fei '
Defines a module that represents a global variable
User.js: Use the Count () method to count the total number of instantiations
' Use strict '; const UTIL = require (' util '); var ncount = 0;function User (sId, sName) {this . Id = sId; This. Name = SName; ncount++;} User.prototype.toString = function () { return Util.format ("id= '%s ', name= '%s '", this.) Id, this. Name);} Module.exports = User;module.exports.count = function () { return ncount;}
App.js
var user = require ('./user '), var psource = [];p source.push (new User (' Liubei ', ' Liu Bei '));p source.push (' Guanyu ', ' Guan Yu ');p Source.push (New User (' Zhangfei ', ' Zhang Fei '));p Source.foreach (function (puser) { console.log (' ${puser.tostring ( } '); Console.log (' Count is ${user.count ()} ');
Console
Id= ' Liubei ', Name= ' Liu Bei ' id= ' Guanyu ', name= ' Guan Yu ' id= ' Zhangfei ', Name= ' Zhang Fei ' count is 3
Nodejs in Visual Studio Code 06. New Module