目录结构
- Apache
- www
- read.txt
- photo.jpeg
- index.html
代码示例
var http = require('http');
var fs = require('fs');
var server = http.createServer();
var wwwDir = './../../Apache/www/'; // 所有读取文件所在的根目录
server.on('request', (req, res) => {
/*
req.url 拿到的路径是 端口号后面的
例如: localhost:3000/index 对应的 path 就是 /index
*/
var url = req.url;
var filePath = 'index.html'; // 路径为 '/' 时 文件路径指向index.html
console.log(`${wwwDir}${filePath}`);
if(url !== '/'){
filePath = url;
}
fs.readFile(`${wwwDir}${filePath}`, (err, data)=>{
if(err){
return res.end('404');
}
res.end(data); //结束响应 并发送响应数据
})
})
server.listen('3000', '127.0.0.1', () => {
console.log('http://localhost:3000/')
})
输入路径
http://localhost:3000/
http://localhost:3000/index.html
http://localhost:3000/read.txt
http://localhost:3000/photo.jpeg