一. Node 中的模块
在 Node 中模块有三种:
1. 具名的核心模块,Node 为 JS 提供了许多服务器级别的 API,这些 API 绝大多数都被包装到了具名的核心模块中.例如:文件操作的 fs 核心模块,服务器构建的 http 核心模块,路径操作的 path 核心模块,操作系统信息的 os 核心模块等。
2. 用户自己编写的文件模块,开发者自己写的 js 文件
3. 第三方模块,从npm服务器下载的第三方包
二. 较常用核心模块
1. fs 核心模块,文件操作
fs 是 file-system 的简写,就是文件系统的意思,在 Node 中如果想要进行文件的操作,就必须引入 fs 核心模块,fs 核心模块中提供了所有文件操作相关的 API。例如下:
1) 读取文件,新建一个js文件和txt文件(内容随便写)
var fs = require('fs')
//读文件
//参数:
// 1.需要读取的文件路径
// 2.回调函数
// 读取成功(data是读取的数据,error是null)
// 读取失败(data是undefined,error是错误对象)
fs.readFile('./test1.txt', function (error, data) {
//console.log(data);
//控制台输出:<Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
//文件存储的其实都是二进制数据,控制台显示为十六进制
//可以通过 toString 方法把其转换为我们能认识的字符
if (error) {
console.log(error);
} else {
console.log(data.toString());//修改处
}
})
效果如下:
2) 写文件,新建一个js文件(和txt文件)
var fs = require('fs')
//写文件
//参数:
// 1.文件路径
// 2.文件内容
// 3.回调函数
// 写入成功(error是null)
// 写入失败(error是错误对象)
fs.writeFile('./test2.txt', 'hello test2', function (error) {
if (error) {
console.log(error)
} else {
console.log('文件写入成功')
}
})
效果如下:
3) 读目录
var fs = require('fs')
//读目录
fs.readdir('./', function (error, files) {
if (error) {
return console.log('目录不存在')
}
console.log(files)
})
效果如下:
2. http 核心模块,构建服务器
新建一个服务器架js文件
//Node 专门提供了一个核心模块:http
//http 可以创建编写服务器
//1. 加载 http 核心模块
var http = require('http')
//2. 使用 http.createServer() 方法创建一个 Web 服务器,返回一个 server 实例
var server = http.createServer()
//3. 监听服务器,注册 request 请求事件,设置请求处理函数(回调函数)
// 当客户端求情过来,就会自动触发服务器的 request 请求事件,然后执行回调函数
// 回调函数参数:
// 1) request 请求对象(可以用来获取客户端的一些信息,例如请求路径)
// 2) response 响应对象(可以用来给客户端发送消息)
server.on('request', function (request, response) {
//response.write() 可以用来给客户端发送响应数据
//response.write('hello')
//response.write(' world!')
//response.end()//结束响应
response.setHeader("Content-type", "application/json")
//最后一定要使用 response.end() 来结束响应,否则客户端会一直等待
response.end('hello');注意:响应数据只能是二进制数据或者字符串
})
//4. 绑定端口号,启动服务器
server.listen(3000, function () {
console.log('服务器启动成功了,可以通过 http://127.0.0.1:3000/ 来访问')
})
效果如下:
3. path 核心模块,路径操作
新建一个js文件
var path = require('path')
//console.log(path.basename('c:/a/b/index.js'))//输出 index,js
//console.log(path.basename('c:/a/b/index.js','.js'))///输出 index
//console.log(path.dirname('c:/a/b/index.js'))///输出 c:/a/b
//console.log(path.extname('c:/a/b/index.js'))///输出 .js
//console.log(path.join('c:/a','b'))//输出 c:\a\b
console.log(path.parse('c:/a/b/index.js'))
效果如下:
4. url 核心模块,可使用 url.parse 方法将路径解析为一个方便操作的对象
新建一个js文件
var url = require('url')
//第二个参数为 true 表示直接将查询字符串转为一个对象(通过 query 属性访问)
let obj = url.parse('http://127.0.0.1:3000/postComment?name=1&message=2',true)
console.log(obj)
console.log(obj.query)
console.log(obj.pathname)
效果如下: