node.js学习之用路由方法获取简单的图文html页面
来源:互联网 发布:网络博客报警有用吗 编辑:程序博客网 时间:2024/06/05 05:55
程序主程序n8_routehtml.js
var http = require('http'); var url = require('url');var router = require('./models/router'); http.createServer(function(request,response){ if(request.url!=="/favicon.ico"){ //清除第2此访问 /*获取要访问的页面*/ pathname=url.parse(request.url).pathname; pathname = pathname.replace(/\//,'');//替换掉前面的///console.log(pathname);//由route调用不同的方法 router[pathname](request,response); }}).listen(3000); console.log('Server running at http://127.0.0.1:3000/');./models/router.js:
//导入文件操作对象var optfile = require("../models/optfile.js");//getRecall作为一个公共的函数,访问不同的页面时,由不同的函数调用function getRecall(res,req){res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'}); function recall(data){res.write(data);res.end('');}return recall;}module.exports={login:function(req,res){//登录页面//res.write("I am login function");recall = getRecall(res,req);optfile.readfile('./views/login.html',recall);},register:function(req,res){//注册页面//res.write("I am register function");recall = getRecall(res,req);optfile.readfile('./views/register.html',recall);},showimg:function(req,res){res.writeHead(200, {'Content-Type':'image/jpeg'}); optfile.readimg('./image/cbd.jpg',res); }}./models/optfile.js:
var fs = require('fs');module.exports={readfile:function(path,recall){//异步读取文件fs.readFile(path,function(err,data){if(err){console.log(err);}else{//res.write(data.toString());recall(data);//res.end('');}});console.log("异步方法执行完毕");},readimg:function(path,res){//异步方式读取图片fs.readFile(path,'binary',function(err,data){if(err){console.log(err);return;}else{res.write(data,'binary');res.end('');}});}}要读取的页面在./views文件夹下
login.html
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>欢迎登陆</title></head><body><h2>welcome to node.js</h2><img src="http://localhost:3000/showimg"/></body></html>
运行结果:
阅读全文
0 0
- node.js学习之用路由方法获取简单的图文html页面
- node.js学习之路由初步
- node.js 简单登录 路由
- JS 之Node节点的 属性、方法 &获取
- 【自己的整理】node.js直接输出一个非常简单的HTML页面
- node.js简单的页面输出
- node.js学习之node的安装
- 学习笔记之php页面中js获取标签元素的ID值方法
- Node.js 灵活的路由
- Node.js 简单页面输出
- js Html页面控件的获取值
- Node.js简单学习
- Node.js 简单学习
- node.js学习笔记_模拟路由
- 【知识整理】Node.js-Koa之路由
- Node.js学习教程之二:node.js的HelloWorld
- 获取html页面内容的方法
- 获取html页面代码的方法
- 多文件同时读写为什么没有单文件读写快?
- bzoj 3018: [Usaco2012 Nov]Distant Pastures
- 自定义任务属性
- Centos 与本地终端 上传、下载 文件
- 更换Homebrew的更新源
- node.js学习之用路由方法获取简单的图文html页面
- MQ的使用场景
- 安装VMware Workstation与Xampp的Apache就启动不了
- flume-ng源码浅析
- 【学习笔记】VOIP以及SIP协议初步熟悉和了解
- gem sorcery的使用
- C#获取CPU温度(OpenHardwareMonitorLib.dll库)
- 这些SEO搜索技巧你会不会用?
- 【Java笔记】try中捕获到异常后跳出try