初识Node.js (fs,path, http)
Node.js 的官网地址:https://nodejs.org/zh-cn/
含义:Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
注意:Node.js 中无法调用 DOM 和 BOM 等 浏览器内置 API。
node.js很强大
基于 Express 框架(http://www.expressjs.com.cn/),可以快速构建 Web 应用
基于 Electron 框架(https://electronjs.org/),可以构建跨平台的桌面应用
基于 restify 框架(http://restify.com/),可以快速构建 API 接口项目
node.js命令:
node - v 查看已安装的版本号
终端上的快捷键:
↑键 快速定位到上一次执行的命令
tab键 快速补全路径
esc键 快速清空当前已输入的命令
cls键 清空终端
1.内置API模块
one:fs文件系统模块
fs.readFile() 方法,用来读取指定文件中的内容
fs.writeFile() 方法, 用来向指定的文件中写入内容
fs.readFile() 语法格式:
fs.readFile ( path [, option ], callback)
参数1:必选参数 ,字符串,表示文件的路径
参数2: 可选参数, 表示用什么编码格式来读取文件
参数3: 必选参数, 文件读取完成后,通过回调函数拿到读取的结果
fs.writeFile() 语法格式:
fs.writeFile ( file, data [, option ], callback)
参数1:必选参数 ,指定一个文件路径的字符串,表示文件的存放的路径
参数2: 必选参数, 表示要写入的内容
参数2: 可选参数, 表示用什么编码格式来读取文件
参数3: 必选参数, 文件写入完成后的回调函数
路径动态拼接:
__dirname 表示当前文件所处的目录
two:path 路径模块
path.join() 方法,用来将多个路径片段拼接成一个完整的路径字符串
const path = require('path')
const fs = require('fs')
// 注意: ../ 会抵消前面的路径
// const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
// console.log(pathStr) // \a\b\d\e
// fs.readFile(__dirname + '/files/1.txt')
fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function(err, dataStr) {
if (err) {
return console.log(err.message)
}
console.log(dataStr)
})
注意:凡是涉及到路径拼接的操作,都要使用 path.join() 方法进行处理。不要直接使用 + 进行字符串的拼接。
使用 path.basename() 方法,可以获取路径中的最后一部分,经常通过这个方法获取路径中的文件名
path.basename ( path [, ext] )
1.path <string> 必选参数,表示一个路径的字符串
2.ext <string> 可选参数,表示文件扩展名
3.返回: <string> 表示路径中的最后一部分
const path = require('path')
// 定义文件的存放路径
const fpath = '/a/b/c/index.html'
// const fullName = path.basename(fpath)
// console.log(fullName) //输出index
const nameWithoutExt = path.basename(fpath, '.html')
console.log(nameWithoutExt) //输出index
const path = require('path')
const fpath = '/a/b/c/index.html' //路径字符串
const fext = path.extname(fpath)
console.log(fext) //输出 .html
three: http 模块
http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。
调用 res.setHeader() 方法,设置 Content-Type 响应头,解决中文乱码的问题
// 1. 导入 http 模块
const http = require("http");
// 2. 创建 web 服务器实例
const server = http.createServer();
// 3. 为服务器实例绑定 request 事件,监听客户端的请求
// req 是请求对象,包含了与客户端相关的数据和属性
server.on("request", (req, res) => {
// // req.url 是客户端请求的 URL 地址
// const url = req.url;
// // req.method 是客户端请求的 method 类型
// const method = req.method;
// const str = `Your request url is ${url}, and request method is ${method}`;
// 定义一个字符串,包含中文的内容
const str = `您请求的 URL 地址是 ${req.url},请求的 method 类型为 ${req.method}`
// 调用 res.setHeader() 方法,设置 Content-Type 响应头,解决中文乱码的问题
res.setHeader('Content-Type', 'text/html; charset=utf-8')
console.log(str);
// 调用 res.end() 方法,向客户端响应一些内容
res.end(str);
});
// 4. 启动服务器
server.listen(8080, function () {
console.log("server running at http://127.0.0.1:8080");
});