NodeJs复习-cnblog
NodeJs 复习
1. 什么是 NodeJS
- node.js 是基于 chorm 浏览器 v8 引擎的JavaScript 运行环境
2. NodeJS 的模块
3. fs 模块(文件读取模块)
// 导入fs文件系统模块
const fs = require('fs')
// 读取文件
fs.readFile('./files/1.txt', 'utf8', function (err, datastr) {
// 失败的结果
console.log(err)
// 成功的结果
console.log(datastr)
})
- 读取成功的判断
const fs = require('fs')
// 读取文件
fs.readFile('./files/1.txt', 'utf8', function (err, datastr) {
if (err === null) {
console.log('文件读取成功' + datastr)
} else {
console.log('文件读取失败' + err.message)
}
})
写入文件
fs.writeFile(file,data[,options],callback)
- options 编码格式,默认 utf8
const fs = require('fs')
// 写入文件
fs.writeFile('./files/2.txt', '666', function (err) {
if (err) {
console.log('写入文件失败' + err.message)
} else {
console.log('写入文件成功' + err)
}
})
文件路径
-
原因:代码在运行时,会以执行 node 命令时所处的目录,动态拼接出文件的完整路径
-
解决方案
- 使用__dirname 代表当前文件所处的目录
const fs = require('fs') fs.readFile(__dirname + '/files/1.txt', 'utf8', function (err, datastr) { if (err) { return console.log('文件读取失败' + err.message) } else { console.log('文件读取成功' + datastr) } })
-
下面介绍的 path 模块
4. path 模块
-
将多个字符串拼接成一个完整的路径字符串
-
语法
path.join([...paths])
- …paths 路径片段序列
const path = require('path')
var str = path.join('a/b/v', '../', '/m/n', 'c')
console.log(str) // a\b\m\n\c
var str2 = path.join(__dirname, './files/1.txt')
console.log(str2) // E:\\nodejs代码\day01\files\1.txt
获取文件路径的最后一个部分
const path = require('path')
var pathstr = 'a/b/c/index.html'
// 获取路径的最后一个部分
var strName = path.basename(pathstr)
console.log(strName) // index.html
// 添加文件扩展名参数,则返回值中不包含文件扩展名
var strName2 = path.basename(pathstr, '.html')
console.log(strName2) // index
获取一个路径名中扩展名的部分
const path = require('path')
// 定义一个文件存放路径
var fpath = 'a/b/c/index.html'
// 获取文件路径中的扩展名
var extName = path.extname(fpath)
console.log(extName) // .html
8.一个时钟案例(拆分 HTML 文件中的 style 标签的内容和 script 标签内的内容)
思路
- 代码实现
// 导入fs模块
const fs = require('fs')
// 导入path模块
const path = require('path')
// 定义一个匹配style标签的正则表达式
// \s 代表任意空白字符,\S代表任意非空白字符,*代表匹配多次,结束标签中的<\/style> 的\用于转义,防止不合法
var regStyle = /<style>[\s\S]*<\/style>/
// 定义一个匹配script标签内容的正则表达式
var regScript = /<script>[\s\S]*<\/script>/
// 获取files下index.html文件的字符串内容
var htmlPath = path.join(__dirname, './index.html')
fs.readFile(htmlPath, 'utf8', function (err, datastr) {
if (err) {
return console.log('读取文件失败' + err.message)
} else {
console.log('读取文件成功')
// 存放文件字符串
var htmlStr = datastr
resloveCss(htmlStr)
resloveJs(htmlStr)
resloveHtml(htmlStr)
}
})
// 将内嵌的style标签的内容写入css文件
function resloveCss(htmlStr) {
// 匹配正则表达式
var styleStr = regStyle.exec(htmlStr)
// 将标签名去除
// console.log(styleStr);
var cssStr = styleStr[0].replace('<style>', '').replace('</style>', '')
var cssPath = path.join(__dirname, './files/index.css')
fs.writeFile(cssPath, cssStr, function (err) {
if (err) {
return console.log('写入文件失败' + err.message)
} else {
console.log('写入index.css成功')
}
})
}
// 将内嵌script标签内的内容写入 js文件中
function resloveJs(htmlStr) {
var scriptStr = regScript.exec(htmlStr)
var jsStr = scriptStr[0].replace('<script>', '').replace('</script>', '')
var jsPath = path.join(__dirname, './files/index.js')
fs.writeFile(jsPath, jsStr, function (err) {
if (err) {
return console.log('写入文件失败' + err.message)
} else {
console.log('写入index.js成功')
}
})
}
// 将html文件中的内嵌式style 和 script 标签的内容替换为 外联式的引用
function resloveHtml(htmlStr) {
var newHtml = htmlStr
.replace(regStyle, "<link rel='stylesheet' href='./index.css'/>")
.replace(regScript, "<script src='./index.js'></script>")
var newpath = path.join(__dirname, './files/index.html')
fs.writeFile(newpath, newHtml, function (err) {
if (err) {
return console.log('html文件写入失败' + err.message)
} else {
console.log('html文件写入成功')
}
})
}
5. http 模块
- 创建 web 服务器
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
// 有关客户端的字符串
var str = `你请求的url地址为${req.url},请求方式为${req.method}`
// 将该字符串作为响应消息发给客户端,并结束这次请求
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(str)
})
server.listen(80, () => {
console.log('http server running at http://10.152.242.223')
})
根据不同 url 响应不同的内容
// 导入http,fs,path
const fs = require('fs')
const http = require('http')
const path = require('path')
// 创建服务器实例
var server = http.createServer()
// 监听服务器实例
server.on('request', (req, res) => {
var url = req.url
// 进行路径拼接
var pathStr = ''
if (url === '/') {
// 默认是首页地址
pathStr = path.join(__dirname, '/clock/index.html')
} else {
// 请求css,js时拼接clock目录
pathStr = path.join(__dirname, '/clock', url)
}
fs.readFile(pathStr, (err, datastr) => {
if (err) {
// 读取到不存在的文件
return res.end('404 not found!')
} else {
// res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(datastr)
}
})
})
// 开启服务器
server.listen(80, () => {
console.log('http server running at http://10.152.242.223')
})
6.模块化
6.1 module.exports 对象
- 在自定义模块中,可以使用 module.exports 对象,将模块内的成员共享出去,供外界使用
- 使用 require()方法导入自定义模块时,得到的就是 module.exports 所指向的对象
示例
- 自定义模块.js
// 在module.exports对象上挂载 username属性
module.exports.username = 'zs'
// 在module.exports对象上挂载sayHello()方法
module.exports.sayHello = function () {
console.log('hello!')
}
const age = 20
module.exports.age = age
- 测试.js
const zdy = require('./06.自定义模块')
console.log(zdy) // {username:'zs',sayHello:[Function(anoymous)],age:20}
注意点
-
使用 require()方法导入模块时,导入的结果,永远以 module.exports 指向的对象为准
-
原因:exports 对象和 module.exports 一开始存放者一样的地址,如果修改 exports 内的地址,而 moudle.exports 的地址部分是改变,暴露的还是 module.exports 指向的对象,反过来也是如此
6. 模块加载机制
6.1 模块优先从缓存中加载
- 模块在第一次被加载时里面的代码会被执行,加载后模块被缓存,多次调用 require()方法不会导致模块的代表被多次执行
示例
- 自定义模块 4
console.log('hello')
- 测试自定义模块 4
require('./17.自定义模块4')
require('./17.自定义模块4')
require('./17.自定义模块4')
- 效果图
6.2 内置模块的加载机制
- 内置模块是由 Node.js 官方提供的,内置模块的加载优先级最高
- 例如,require(’fs’)始终返回内置的 fs 模块,即使在 node_modules 目录下有名字相同的包也叫做 fs
6.3 自定义模块的加载机制
- 使用 require()加载自定义模块时,必须指定以./或../开头的路径标识符,在加载自定义模块时,如果没有指定./或../这样的路径标识符,则 node 会把他当作内置模块或第三方模块进行加载
6.4 第三方模块的加载机制
6.5 目录作为模块
7 express
npm i express@4.17.1
- 创建最基本的 web 服务器
const express = require('express')
const app = express()
app.listen(80, () => {
console.log('express server running at http:127.0.0.1')
})