初识nodejs27

来源:互联网 发布:mac怎么用触摸板右键 编辑:程序博客网 时间:2024/05/17 11:57

使用fs模块实现行为表现分离


结构,行为,表现的分离.
fs文件操作


var http =require("http");var url =require("url");var fs =require("fs");var server = http.createServer();var htmlDir =__dirname + "/html/";/*__dirname是一个全局变量,返回值是当前文件所在的路径,*//*读取数据的函数 *类似于express框架*/function sendData(file, req, res) {    fs.readFile( file, function(err, data) {        if (err) {            res.writeHead(404, {                'content-type' : 'text/html;charset=utf-8'            });            res.end('<h1>页面被狗狗吃掉了</h1>');        } else {            res.writeHead(200, {                'content-type' : 'text/html;charset=utf-8'            });            res.end(data);        }    } );}server.on("request",function( req,res ){    var urlStr = url.parse(req.url);    switch(urlStr.pathname){        case "/" :            sendData(htmlDir+"index.html",req,res);            break;        case "/user" :            sendData(htmlDir+"user.html",req,res);            break;        default:            sendData(htmlDir+"err.html",req,res);            break;    }})server.listen(8080,"localhost");server.on("listening",function(){    console.log("listening...");})