1 Node.js module and package
1.1 module
Node.js itself provides many modules. Each module implements a function, such as file operation module fs, HTTP module for building HTTP services, etc. each module is a javascript file and can write its own module.
Each node js is a node js module, including JavaScript file (. js), json text file (. json) and binary module file (. Node)
1.1.1 use of modules
Module. Is used in the module Exports and exports provide external interfaces to facilitate the introduction of modules to be used in other modules and the creation of new modules JS and provide external interfaces.
Use exports to provide an interface
function hello() { console.log("Hello"); } function world() { console.log("World"); } exports.hello = hello; exports.world = world;
Use module Exports provides an interface
function Hello() { this.hello = function() { console.log("Hello"); }; this.world = function() { console.log("World"); }; } module.exports = Hello;
1.1.2 reference module
Use the require() reference to create a module, and the parameter is the path of the module.
Refer to the module with the interface provided by exports
var hello = require("./test.js"); hello.hello(); //==> Hello hello.world(); //==> World
Reference module Exports modules that provide interfaces
//module.exports exports the Hello function and saves it in the Test variable var Test = require("./test.js"); //Use Test() as a constructor and create an object to use var demo = new Test(); demo.hello(); //==> Hello demo.world(); //==> World
1.2 module. Differences between exports and exports
Each module has a module object, which is a reference to the current module. module. The exports object is built by the module system, and exports can be regarded as a module References to the exports object.
When requiring () a module, use module The value of exports shall prevail. In some cases, module The values of exports and exports are different.
// module.exports is the same as exports var m = {}; // Represents a module var e = m.e = {}; // e stands for exports and m.e stands for module exports m.e.a = 5; e.b = 6; console.log(m.e); // Object { a: 5, b: 6 } console.log(e); // Object { a: 5, b: 6 }
// module.exports and exports are different var m = {}; // Represents a module var e = m.e = {}; // e stands for exports and m.e stands for module exports m.e = { c: 9 }; // m. The object referenced by E (module.exports) has been changed e.d = 10; console.log(m.e); // Object { c: 9 } console.log(e); // Object { d: 10 }
1.2 package
Packages can organize multiple modules with dependencies and encapsulate multiple modules for easy management.
Node.js adopts the CommonJS specification. A javascript file is a module. A package is a folder. The package must contain a file named package JSON file. The bin folder in the package stores binary files, the lib folder stores javascript files, the doc folder stores documents, and the test folder stores unit tests.
1.2.1 package directory
The package directory must contain package JSON file, CommonJS is used to describe the package, and should contain the following fields:
- Name: the name of the package, which is unique and can only contain characters, underscores and numbers;
- Version: the version number of the package;
- Description: description of the package;
- keywords: keyword array, used for searching;
- Home page: project home page;
- bugs: address of submitting bug;
- liciense: license;
- maintainers: maintainer array;
- Contributors: contributors array;
- repositories: project warehouse hosting address array;
- Dependencies: package dependencies.
example:
{ "name": "Kyxy", "description": "Kyxy test package.", "version": "0.1.0", "keywords": [ "kyxy", "nodejs" ], "maintainers": [{ "name": "test", "email": "test@kyxy.com" }], "contributors": [{ "name": "test", "web": "http://www.kyxy.com/" }], "bugs": { "mail": "test@kyxy.com", "web": "http://www.kyxy.com/" }, "licenses": [{ "type": "Apache License v2", "url": "http://www.apache.org/licenses/apache2.html" }], "repositories": [{ "type": "git", "url": "http://github.com/test/test.git" }], "dependencies": { "webkit": "1.2", "ssl": { "gnutls": ["1.0", "2.0"], "openssl": "0.9.8" } } }
1.3 npm package management tool
npm is node JS package management tool, npm defines the package dependency standard, uses npm to download third-party packages and manage locally downloaded third-party packages.
Query package information: npm info express Installation package: sudo npm install express Update package: sudo npm update express Uninstall package: sudo npm uninstall express
2 Events module
Node.js, many objects emit events: FS An event is emitted when readstream opens a file. All emitted event objects are events An instance of EventEmitter can be accessed through require("events"); Get the events module.
Hump nomenclature is recommended for event naming. Add functions to the object. When the object sends an event, the corresponding functions are executed (these functions are called listeners); First, assign the function to the object (set it as a listener) and call the function when the object emits an event
2.1 Class: events.EventEmitter
Through require ("events") EventEmitter gets the EventEmitter class. When the EventEmitter object encounters an error, the error event is triggered;
The error event is on node JS is a special event (if no listener triggered by error event is set), print out the stack tracker by default and exit the program.
2.2 adding listeners
There are two ways to add a listener to an event, which have exactly the same functions: parameter event and handler (listener)
- emitter.addListener(event, listener) :
- emitter.on(event, listener): listen all the time
//import http module var http = require("http"); //create a http server var server = http.createServer(); //bind a listener for server`s request Event server.on("request", function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write("Tracy"); console.log("Kyxy"); res.end(); }); //listen ip:127.0.0.1 port:1337, if requested, execute the listener function server.listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
Run the above code, enter 127.0.0.1:1337 in the browser address bar, you can see Tracy, and the console outputs Kyxy
2.3 listener that executes only once
Use emitter The event listener bound to the once (event, listener) method will execute only once, and then the event will be deleted.
var http = require('http'); var server = http.createServer(); // Bind the handler for the request event, and the event will be executed only once server.once('request', function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('shiyanlou'); console.log('shiyanlou'); res.end(); }); server.listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
Run the above code, enter 127.0.0.1:1337 in the browser address bar, you can see Tracy, and the console outputs Kyxy. If you refresh the page again, it will not be displayed again, because the event will be executed only once.
2.4 removing the listener
Use emitter The removelistener (event, listener) method removes the handler bound to the request event of the object.
//import http module var http = require("http"); //create a http server var server = http.createServer(); function callback(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write("Hello World"); console.log("Hello World"); res.end(); } //bind a listener for server`s request Event server.on("request", callback); //remove a listener for server`s request Event server.removeListener("request", callback); server.on("request", function(req, res) { res.writeHead(200, { 'Content-Type': 'text/json' }); res.write("I`m back"); console.log("LMD"); res.end(); }); //listen ip:127.0.0.1 port:1337, if requested, execute the listener function server.listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
Run the above code, enter 127.0.0.1:1337 in the browser address bar, you can see Im back, and the console outputs LMD, but there is no Hello World, because the listener callback 'has been removed.
2.4 remove all listeners
Use emitter Removealllisteners ([event]) to remove all listeners listening for event events on the object.
//import http module var http = require("http"); //create a http server var server = http.createServer(); function talk(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write("haha"); console.log("xixi"); res.end(); }function fruit(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write("apple"); console.log("leomon"); res.end(); } //bind listeners for server`s request Event server.on("request", talk); server.on("request", fruit) //remove listeners from server`s request Event server.removeAllListeners("request"); server.on("request", function(req, res) { res.writeHead(200, { 'Content-Type': 'text/json' }); res.write("I`m back"); console.log("LMD"); res.end(); }); //listen ip:127.0.0.1 port:1337, if requested, execute the listener function server.listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
Remove all event listeners bound to the server, so only Im back is displayed and LMD 'is output.
2.5 set the maximum binding number of listeners
emitter.setMaxListeners(n) can set the maximum number of listeners that can be bound to the same event. By default, more than 10 will prompt warning messages (which can help find memory leaks). Not all event triggers are limited to 10. You can set this method. If it is set to 0, there is no limit.
2.6 user defined events
Use emitter emit(event, [arg1], [arg2], [...]), Custom events can be triggered.
//import http module var http = require("http"); //create a http server var server = http.createServer(); server.on("myevent", function(arg) { console.log(arg); }); server.emit("myevent", "Kyxy"); server.on("request", function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write("Tracy"); res.end(); }); //listen ip:127.0.0.1 port:1337, if requested, execute the listener function server.listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
2.7 viewing the number of event bound listeners
Use events EventEitter. Listener count (emitter, event) can view the number of event listeners.
var http = require("http"); var events = require("events"); var server = http.createServer(); server.on("request", function(req, res) { res.writeHead(200, {"Content-Type": "text/plain"}); res.write("kyxy"); console.log("kyxy"); res.end(); }); server.on("request", function(req, res) { res.writeHead(200, {"Content-Type": "text/plain"}); res.write("Tracy"); console.log("Tracy"); res.end(); }); server.listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/'); var num = events.EventEmitter.listenerCount(server, "request"); console.log(num); //2
The console interface outputs the number 2 because the server binds two listeners to the 'request' event.