一、全局模块——任何时候都可直接使用,不需要额外引入
例如,获取环境变量 process.env
先通过计算机看一下系统中的环境变量
在js中简单的输出process.env
console.log(process.env)
执行代码,可以看到,输出结果中包含了上图系统中环境变量。
二、系统模块——需要require,但不需要单独下载
例一、path模块,用于处理文件路径和目录路径的实用工具
let path = require('path');
var str = 'node/images/bg.jpg';
console.log('dirname -',path.dirname(str));
console.log('basename -',path.basename(str));
console.log('extname -',path.extname(str));
执行结果如下:
例二、fs模块,用于文件的读写操作
let fs = require('fs');
// 异步写文件
fs.writeFile('./nie.txt','123',(err)=>{
console.log('异步写文件')
if(err){
console.log(err)
}
})
// 同步写文件
let data1 = fs.writeFileSync('./nie.txt','ABC');
console.log('同步写文件',data1);
// 追加文件内容
fs.writeFile('./nie.txt','456',{flag:'a'},(err)=>{
console.log('追加文件内容')
if(err){
console.log(err)
}
})
// 异步读文件
fs.readFile('./nie.txt',(err,data)=>{
if(err){
console.log(err)
}else {
console.log('异步读文件:',data.toString())
}
})
// 同步读文件
let data2 = fs.readFileSync('./nie.txt')
console.log('同步读文件:',data2.toString());
执行结果如下:
例三、http模块,用于搭建服务和请求处理
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>node模块</title>
</head>
<body>
<p>node模块</p>
<img src="images/node.jpeg">
</body>
</html>
// index.js
let http = require('http');
let fs = require('fs');
http.createServer((req,res)=>{
fs.readFile(`./${req.url}`,(err,data)=>{
if(err){
res.writeHead(404);
res.end('404 Not Found');
}else{
res.end(data);
}
})
}).listen(8080)
执行代码后,在浏览器中访问 http://localhost:8080/index.html,结果如下:
例四、os模块,用于操作系统信息的获取
// demo.js
const os = require('os');
// 获取当前系统的CPU数量
const cpus = os.cpus();
console.log(cpus.length)
// 获取内存信息(字节)
const total = os.totalmem();
console.log(total);
//获取剩余内存(字节)
const free = os.freemem();
console.log(free)
执行结果:
三、自定义模块
- require - 如果有路径,就去路径里面找,否则去node_modules里面找,若没有node_modules,则去node安装目录里找。
例一、批量导出数据
// module.js
// 批量导出
module.exports={
a:1,
b:2
}
// index.js
const mod = require('./module');
console.log(mod)
输出结果
例二、导出function
// module.js
// 导出function
module.exports=function () {
console.log('nie');
}
// index.js
const mod = require('./module');
mod();
输出结果
例三、导出class
// module.js
// 导出class
module.exports=class {
constructor(name){
this.name = name
}
show(){
console.log(this.name)
}
}
// index.js
let people = new mod('Annie');
people.show();
输出结果