node 實現靜態服務server.js

原文鏈接:https://blog.csdn.net/Jacoh/article/details/84194685

先下載安裝node.js 鏈接地址:https://nodejs.org/zh-cn/

安裝完可以用以下命令查看版本,顯示版本號則代表安裝成功:

node -v

>>v10.16.3

將下面代碼保存爲server.js,然後放到再需要靜態訪問的目錄下,執行命令:node server.js,
即可通過url 地址訪問對應文件。(默認端口:8888) 默認:http://localhost:8888/www/app.html

// 引入相應模塊
var http = require('http'),
	 url = require('url'),
	path = require('path'),
	  fs = require('fs');
	  
var port = process.argv[2] || 8888;

var types = {
	'mp3': 'audio/mpeg',
	'html': 'text/html',
	'js': 'application/javascript'
},
site = 'http://localhost:' + port;

http.createServer(function (request, response) {
    var uri = url.parse(request.url).pathname,
    filename = path.join(__dirname, uri);
    
    fs.exists(filename, function (exists) {
       if (!exists) {
           response.writeHead(404, {'Content-Type': 'text/plain', 'X-my-param':'zcyue'});
           response.write('404 Not Found\n');
           response.end();
           return;
       }

       if(!fs.lstatSync(filename).isDirectory()) {
           var type = filename.split('.');
           type = type[type.length - 1];
           response.writeHead(200, { 'Content-Type': types[type] + '; charset=utf-8' });
           fs.createReadStream(filename).pipe(response);
        } else {
           response.writeHead(301, {'Location': site + '/www/app.html' });
           response.end();
        }
    });
}).listen(parseInt(port, 10));

console.log('Static file server running at\n => ' + site + '/\nCTRL + C to shutdown');

其他鏈接:https://blog.csdn.net/cckevincyh/article/details/78637576

gihub地址(可放靜態頁):https://github.com/guiyangyang/node.js-staticWebsite

簡單頁面直接輸入(http://localhost:9090/ 就能訪問主頁):https://www.jianshu.com/p/82714f49fa2b

var http = require("http");
var path = require("path");
var fs = require("fs");
var url = require("url");

var server = http.createServer(function(req,res){
    routePath(req,res);
});

server.listen(9090);
var port = process.argv[2] || 9090;
site = 'http://localhost:' + port;

function routePath(req,res){
    var pathObj = url.parse(req.url,true);

    switch(pathObj.pathname){
        case "/getWeather":
        var ret;
        if(pathObj.query.city == "beijing"){
            ret = {
                "city": "beijing",
                "weather": "sunny"
            }
        }else{
            ret = {
                "city": pathObj.query.city,
                "weather": "Unknow"
            }
        }
        res.end(JSON.stringify(ret));
        break;
        default:
        staticRoot(req,res);
    }

}

function staticRoot(req,res){
    var pathObj = url.parse(req.url,true);

    var filePath = path.join(__dirname,pathObj.pathname);

    if(fs.existsSync(filePath)){
        var pathnameDir = fs.lstatSync(filePath);
        if(pathnameDir.isDirectory()){
            filePath = path.join(filePath,"index.html");
        }
    }

    fs.readFile(filePath,"binary",function(error,fileContent){
        if(error){
            res.writeHead(404,"not found");
            res.write("<h1>404 Not Found</h1>");
            res.end();
        }else{
            res.writeHead(200,"OK");
            res.write(fileContent,"binary");
            res.end();
        }
    });
}

console.log('Static file server running at\n => ' + site + '/\nCTRL + C to shutdown');

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章