node 創建靜態服務器並自動打開瀏覽器


node 作為一門偏向后端的技術,提供了可以讓我們js 在服務器上運行的平台,為我們前端工程師實現項目前端工程化,帶來了眾多便利。同時,它也可以很方便的創建靜態服務器,可以直接連接數據庫、、、實現多種功能,可以說,對於一個前端工程師如果精通了 node ,那么開發效率可以大大的提高,下面就是一段 利用 node 搭建的一個項目服務器,來啟動項目並在默認瀏覽器里自動打開。

 

var http = require('http'), // 引入需要的模塊
    fs = require('fs'),//引入文件讀取模塊
    cp = require('child_process'),  // 可自動打開瀏覽器模塊
	url  = require("url"),
    path = require("path");
    
    
http.createServer(function (req, res) {
    var pathname=__dirname+url.parse(req.url).pathname;  // 對於文件路徑統一處理
    if (path.extname(pathname)=="") {
        pathname+="/html/";  // 欲打開文件的目錄
    }
    if (pathname.charAt(pathname.length-1)=="/"){
        pathname+="index.html";  // 默認打開的文件
    }
    fs.exists(pathname,function(exists){
        if(exists){
            switch(path.extname(pathname)){ // 不同文件返回不同類型
                case ".html":
                    res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                case ".js":
                    res.writeHead(200, {"Content-Type": "text/javascript"});
                    break;
                case ".css":
                    res.writeHead(200, {"Content-Type": "text/css"});
                    break;
                case ".gif":
                    res.writeHead(200, {"Content-Type": "image/gif"});
                    break;
                case ".jpg":
                    res.writeHead(200, {"Content-Type": "image/jpeg"});
                    break;
                case ".png":
                    res.writeHead(200, {"Content-Type": "image/png"});
                    break;
                default:
                    res.writeHead(200, {"Content-Type": "application/octet-stream"});
            }
            fs.readFile(pathname,function (err,data){
            	console.log((new Date()).toLocaleString() +" " +pathname);
                res.end(data);
            });
        } else {  // 找不到目錄 時的處理
            res.writeHead(404, {"Content-Type": "text/html"});
            res.end("<h1>404 Not Found</h1>");
        }
    });
    
}).listen(8889, "127.0.0.1");  // 監聽端口

console.log("Server running at http://127.0.0.1:8889/");

cp.exec('start http://127.0.0.1:8889/');  // 自動打開默認瀏覽器

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM