Node.js custom method to implement file routing function

一个新手
Release: 2017-09-22 09:59:03
Original
1418 people have browsed it

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); } }); }
Copy after login

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); });
Copy after login



3. Home page module response

/** * 主页内容响应处理 */ exports.write=function(res){ res.writeHead(200,{'Content-Type':'text/html'}); res.write(''); res.write('

主页内容2

'); res.end(); }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!