目录
Node.js:
首先,我们来思考一下JS为什么可以被浏览器解析。

其次,为什么JS可以操作DOM和BOM。

再次,我们了解一下JS运行环境:





fs模块:
读取文件:


写入文件:


实际代码:
const fs=require('fs')
let getData=null
//读文件
fs.readFile('./look before use.txt','utf8',function (err,data) {
if (!err){
getData=data
console.log(getData)
}else{
console.log(data)
}
})
//写文件
fs.writeFile('File/needChange.txt','我是修改后的内容','utf8',function () {
console.log('changed')
})
运行结果:

路径动态拼接的问题:


但是这样会导致移植性差的问题。下面我们来看看解决方法:
使用_dirname来解决此问题。

path路径模块:

路径拼接:

获取文件名:

获取文件扩展名:

上面几个方法的示例代码:
const path=require('path')
const fs=require('fs')
//需要注意的是../会抵消上一个传入的路径片段
let pathDir=path.join(__dirname,'/File/needRead.txt')
console.log(pathDir)
//获取文件名字
let pathFileName=path.basename(pathDir,'.txt')
console.log(pathFileName)
//获取扩展名
let getExtName=path.extname(pathDir)
console.log(getExtName)
使用fs和path时,需要注意的几点:

http模块:





创建web服务器:





示例代码:
const http=require('http')
const server=http.createServer()
server.on('request',(req, res) => {
console.log('someone visit!')
})
server.listen(8099,function () {
console.log(`http server run in http://127.0.0.1:8099 `)
})
运行结果:

req请求对象:

res请求对象:
解决中文乱码问题:
设置回应头Content-Type。
res.setHeader('Content-Type','text/html;charset=utf-8')
下面我把整个服务器的流程代码和目录情况展示:
首先是服务器的JS代码:
const fs=require('fs')
const path=require('path')
const http=require('http')
//初始化服务器
const server=http.createServer()
//服务器请求时触发
server.on('request',(req, res) => {
console.log('someone visit!')
//设置响应头编码
res.setHeader('Content-Type','text/html;charset=utf-8')
if (req.url==='/'||req.url==='/index.html'||req.url==='/index.php'){
fs.readFile(__dirname+'/File/serverTestPort/index.html','utf8',function (err,data) {
if (err){
res.end('404 Not Found')
}else{
res.end(data)
}
})
// res.end(`您访问了【 ${req.url}】, 你使用了【 ${req.method}】`)
}else{
//使用end()回应请求。
fs.readFile(__dirname+'/File/serverTestPort/404.html','utf8',function (err, data) {
if (err){
res.end('404 Not Found')
}else{
res.end(data)
}
})
}
})
//服务器开始监听
server.listen(8099,function () {
console.log(`http server run in http://127.0.0.1:8099 `)
})
其次是目录情况:

上面就是服务器的搭建全流程。
服务器搭建思路:

本文介绍了Node.js的基础知识,包括JS在浏览器中的解析原理和DOM/BOM操作。接着详细讲解了fs模块的读写文件操作,以及如何使用path模块动态拼接和处理路径。此外,还展示了如何创建一个简单的HTTP服务器,处理req请求对象和res响应对象,以及设置响应头解决中文乱码问题。最后,通过实例代码展示了服务器搭建的完整流程。

被折叠的 条评论
为什么被折叠?



