1.练习目录如下
demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>我是用来测试的</h1> <img src="./showimg" alt="" style="display: inline-block;width: 100px;height: 100px;"> </body> </html>
整合后的操作文件的 js : operate_file.js
const fs = require('fs'); module.exports = { readSync: (path, fn) => { //同步读取文件 let data = fs.readFileSync(path, 'utf-8'); doFn(fn,data); }, readAsync: (path, fn) => { fs.readFile(path, 'utf-8', (err, data) => { if (err) { throw err; } else { doFn(fn,data); } }); }, writeSync: (file,data, fn) => { //同步写入 fs.writeFileSync(file, data, 'utf-8'); doFn(fn); }, writeAsync: (file,data, fn) => { //异步写入 fs.writeFile(file,data,'utf-8',(err)=>{ if(err){ throw err; }else { doFn(fn); } }); }, readImgSync : (path,fn)=>{ //同步获取图片 let data = fs.readFileSync(path,'binary'); doFn(fn,data); }, readImgAsync : (path,fn)=>{ //异步获取图片 fs.readFile(path,'binary',(err,data)=>{ if(err){ throw err; }else{ doFn(fn,data); } }); } }; //执行fn function doFn(fn,data) { if(typeof fn === 'function'){ if(typeof data !=='undefined'){ fn(data); }else{ fn(); } } }
router.js
const operate = require('./operate_file'); module.exports = { login: (res) => { operate.readAsync('./my_directory/demo.html', (data) => { judgeData('text',res,data); }); }, showimg : (res)=>{ operate.readImgAsync('./img/demo.jpg',(data)=>{ judgeData('img',res,data); }); } }; //通过请求数据类型来设置头部信息 text :字符串类型 img :图片类型 const judgeData = (type, res, data) => { if (type === 'text') { res.setHeader('Content-type', 'text/html;charset= utf-8'); res.write(data); }else if(type === 'img'){ res.setHeader('Content-type','image/jpeg'); res.write(data,'binary'); } res.end(); //断开连接 };
demo.js
const log = require('./router.js'); const url = require('url') //导入url const http = require('http'); //导入http const hostname = '192.168.1.108'; //ip地址 随便写 如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址 const port = 3000; //端口号 const server = http.createServer((req, res) => { //创建一个server res.statusCode = 200; if (req.url !== '/favicon.ico') { //清除二次访问 let url_ = url.parse(req.url).pathname.replace(/\//,''); if(judgeRouter(url_)){ log[url_](res); } } }); server.listen(port, hostname, () => { //监听server console.log(`服务器运行在http://${hostname}:${port}/`); }); //判断是否有这个路由 const judgeRouter = (url_name) => { if (typeof log[url_name] !== 'undefined') { return url_name; } else { console.log('不存在该路由'); return false; } };启动服务,输入 http://192.168.1.108:3000/login 即可看到效果