node根据url跳转页面

node根据url跳转页面

fs模块--文件操作

  1. 异步读取
      fs.readFile( url , code , callback);

  2. 同步读取
      fs.readFileSync( url , code );

var http = require('http');
// url 做路径解析
var url = require('url');
// fs 读写文件
var fs = require('fs');
// node 服务
var server = http.createServer();
// 获取html相对路径
var htmlDir = __dirname + '/html/';

// 处理url请求的数据
function sendData(file, req, res) {
    fs.readFile(file, function (err, data) {
        if (err) {
            res.writeHead(404, {
                'content-type': 'text/html'
            });
            res.write('<h1>404<h1/>');
            res.end();
        } else {
            res.writeHead(200, {
                'content-type': 'text/html'
            });
            res.write(data);
            res.end();
        }
    });
}
// 监听服务开启
server.on('listening', function () {
    console.log('listen..');
});
server.on('request', function (req, res) {
    // 获取url后面的路径
    var urlStr = url.parse(req.url);
    switch (urlStr.pathname) {
        // localhost:8080/
        case '/':
            // 首页
            sendData(htmlDir + 'index.html', req, res);
            break;
        // localhost:8080/new
        case '/new':
            // 首页
            sendData(htmlDir + 'new.html', req, res);
            break;
        // localhost:8080/b
        default:
            sendData(htmlDir + 'error.html', req, res);
            break;
    }
});
server.listen(8026, 'localhost');

转载于:https://www.cnblogs.com/Hsong/p/8992573.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值