统一处理文件读取路径
- 我们知道
apache服务器
中有个www文件夹
,里面存放的文件可以通过apache服务器
进行访问,我们可以试着实现一下,当然上一节用if..else...
也可以做,但是如果文件很多的话,总不能写一大堆的判断吧,那么这一节就来找规律,避免大量的if...else...
判断。
例:
- 首先,在别的地方定义一个
www
文件夹
image.png
- 然后,在新建一个
likeApache.js
文件
**likeApache.js**
const http = require('http');
const fs = require('fs');
let server = http.createServer();
let wwwDir = 'E:/day day up/14Nodejs教程精讲(7天+5天赠送)/www';
server.on('request', function(request, response) {
let url = request.url;
if(url == '/') {
fs.readFile(wwwDir + '/index.html', function(error, data) {
if(error) {
return response.end('404 not found');
}
response.end(data);
})
}else if (url == '/timg.jpg') {
fs.readFile(wwwDir + '/timg.jpg', function(error, data) {
if(error) {
return response.end('404 not found');
}
response.end(data);
})
}
})
server.listen(8080, function() {
console.log('Server is running...')
})
- 注意:这里面已经做了改变,将绝对路径的公共部分保存在了
wwwDir
的变量当中。
- 然后,在命令行中运行
likeApache.js
文件
PS E:\good good study\NodeJs> node .\likeApache.js
Server is running...
-
- 接着,在浏览器中输入
localhost:8080
可以看到
- 在接着,在浏览器中输入
localhost:8080/timg.jpg
可以看到
image.png
- 接下来,我们就开始找规律了
wwwDir + '/index.html'
wwwDir + '/timg.html'
- 我们知道,
request.url
返回的就是localhost:8080
后面的路径,这么一看这个'/index.html'
和'/timg.html'
不就是request.url
返回的url
路径吗,所以我们可以将上面的路径改写一下wwwDir + url
这样就完事了
所以,likeApache.js
文件可以接着改写一下
const http = require('http');
const fs = require('fs');
let server = http.createServer();
let wwwDir = 'E:/day day up/14Nodejs教程精讲(7天+5天赠送)/www';
server.on('request', function(request, response) {
let url = request.url;
let filePath = '/index.html'
if(url != '/') {
filePath = url;
}
fs.readFile(wwwDir + filePath, function(error, data) {
if(error) {
return response.end('404 not found');
}
response.end(data);
})
})
server.listen(8080, function() {
console.log('Server is running...')
})
- 这里只要判断
url
不等于/就好了,这样能少写个判断,(●'◡'●)