Node jumps the page according to the url

Node jumps the page according to the url

fs module -- file operations

  1. Asynchronous read
      fs.readFile( url , code , callback);

  2. Synchronous read
      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');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325280712&siteId=291194637