Home > Article > Web Front-end > Let’s talk about modular development of Node.js
This article introduces you to the modular development of Node.js, which has certain reference value. Interested friends can refer to it.
Modules in node.js are mainly divided into three categories: built-in modules, third-party modules and Custom modules. [Recommendation: node.js video tutorial]
API provided by the Node operating environment. Because these APIs are based on It is developed in a modular way, so we also call the API provided by the Node operating environment as a system module.
Commonly used built-in modules are: fs, os, path, EventEmitter, http.
1. System module fs (file operating system)
//Read file
fs.reaFile('File path/file name'[ ,'File encoding'], callback);
fs.readFile('../index.html', "utf8", (err,data) => { if (err != null) { console.log(data); return; } console.log('文件写入成功'); });
//Synchronous writing code
console.log('start...') var data = fs.writeFileSync('./abc.txt','hello') console.log(data) console.log('end...')
//Asynchronous writing code
console.log('start...') fs.writeFile('./hello.txt','hello world!',function(err){ if(err) throw err console.log('success!') }) console.log('end...')
2. System module path(path)
path.dirname() Returns the part of the path that represents the folder.
path.extname() Returns the extension of the path.
3.events (event trigger)
The events module only provides one object: events.EventEmitter. The core of EventEmitter is the encapsulation of event triggering and event listener functions.
You can access this module through require("events");.
var events = require('events') var emitter = new events.EventEmitter() //绑定事件 emitter.on('abc', function(){ console.log('abc事件执行了...') }) //触发事件 emitter.emit('abc')
4.https (Hypertext Transfer Protocol)
Configuration server
var http = require('http') //创建服务器对象 var app = http.createServer(function(req,res){ res.write('<h1>hello</h1>') res.write('<ul><li>a</li><li>b</li><li>c</li></ul>') res.end() }) //监听端口,开启服务 app.listen(8080, function(){ console.log('server success!') })
Module member export
module.exports = function() { // ... }
Module member import
const 变量 = require('方法')
Those written by others with specific functions that we can use directly Modules are third-party modules. Since third-party modules are usually composed of multiple files and placed in a folder, they are also called packages.
The above is the detailed content of Let’s talk about modular development of Node.js. For more information, please follow other related articles on the PHP Chinese website!