1. Create routing processing definition
//获取http模块 var http = require('http'); //文件 模块 var fs = require('fs'); //404文件 var error = "./view/404.html"; //实现文件 相应函数以及404错误相应函数 var Response = function (res, filePath) { //读取 文件,然后给客户端 相应 fs.readFile(filePath, function (err, data) { if (err) { if (filePath != error) //如果出错输出404页面 Response(res, error); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(data); } }); }
2. Create a server and monitor routing processing
//创建和启动服务器 var server = http.createServer(function (req, res) { console.info(req.url); //判断 URL,提供 不同的路由 var url = req.url; if (url == '/index' || url == '/') { //主页 var index = require('../view/index'); index.write(res); } else { //制定文件输出view下的文件内容 Response(res, './view' + url); } }); //启动服务器 server.listen('3000', function () { var address = server.address(); console.info(address); console.info('服务器启动成功:http://localhost:%s', address.port); });
3. Home page module response
/** * 主页内容响应处理 */ exports.write=function(res){ res.writeHead(200,{'Content-Type':'text/html'}); res.write('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'); res.write('<h1>主页内容2</h1>'); res.end(); }
The above is the detailed content of Node.js custom method to implement file routing function. For more information, please follow other related articles on the PHP Chinese website!