nodejs運行前端項目

有時候咱們會建立一些小項目,只有幾個簡單html,沒有引入一些前端框架,也沒有使用webpack,那咱們要如何讓代碼在咱們本地跑起來呢?javascript

固然是有不少種方法,IIS、wampserver等等好多均可以用,這裏只是說道純粹用node就把項目跑起來,配置簡單。css

前提是你要安裝好了nodejs,安裝方法,去百度一下大把。html

如今假設你的文件目錄以下前端

  • index
    • templates
      • index.html
    • static
      • js
        • index.js
      • css  
        • index.css

 

如今須要在index同級目錄新建兩個文件server.js:java

var PORT = 8089;//監聽的端口

var http = require('http');
var url=require('url');
var fs=require('fs');
var help=require('./help').types;//
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("index", pathname);    //這裏設置本身的文件名稱;
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = help[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

help.jsnode

 1 exports.types = {
 2   "css": "text/css",
 3   "gif": "image/gif",
 4   "html": "text/html",
 5   "ico": "image/x-icon",
 6   "jpeg": "image/jpeg",
 7   "jpg": "image/jpeg",
 8   "js": "text/javascript",
 9   "json": "application/json",
10   "pdf": "application/pdf",
11   "png": "image/png",
12   "svg": "image/svg+xml",
13   "swf": "application/x-shockwave-flash",
14   "tiff": "image/tiff",
15   "txt": "text/plain",
16   "wav": "audio/x-wav",
17   "wma": "audio/x-ms-wma",
18   "wmv": "video/x-ms-wmv",
19   "xml": "text/xml"
20 };

而後再index文件夾的同級目錄下運行:webpack

node http.js 

瀏覽器中輸入:web

http://localhost:8089/templates/index.htmljson

就能夠打開你的項目了,只是沒有熱更新,要手動刷新,但起碼跑起來了瀏覽器

相關文章
相關標籤/搜索