1. 程式人生 > >nodejs運行前端項目

nodejs運行前端項目

sts bpa list app 沒有 自己的 ava lis ash

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

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

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

現在假設你的文件目錄如下

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

現在需要在index同級目錄新建兩個文件server.js:

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.js

 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文件夾的同級目錄下運行:

node http.js 

瀏覽器中輸入:

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

就可以打開你的項目了,只是沒有熱更新,要手動刷新,但起碼跑起來了

nodejs運行前端項目