1.創建一個js頁面http.js (黃色背景部分改為自己項目的文件夾名字)
var PORT = 3000;//項目在本地運行的端口號
var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;//
var path=require('path');
var server = http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
var realPath = path.join("www2", 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 = mine[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 + ".");
2.創建一個js頁面mine.js
exports.types = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
3.這兩個js文件和你的項目文件放在同一個文件夾里,
4.在當前文件按着shift+鼠標右擊==》點擊在此處打開Powershell窗口(s) ==》輸入node http.js ==>回車==》會提示你的項目運行端口號:Server runing at port: ****.==》打開網頁網址輸入:http://127.0.0.1:****/index.html
注意:****是端口號,index.html是你當前項目要打開的首頁,如果你運行之后報錯了,修改過錯誤之后記得在Powershell窗口重新輸入node http.js運行項目
eg:打開文件夾
可以cmd進入當前文件夾或者在當前文件按着shift+鼠標右擊==》點擊在此處打開Powershell窗口(s) ==》或者有安裝了git的可以直接在當前文件鼠標右擊==》點擊Git Bash here進入
我當前的頁面是shif+鼠標右擊進入的
輸入node http.js ==>回車鍵 之后的效果 我當前的項目是運行在3000端口上的
網址輸入:該項目就可以運行了
我的項目的文件夾: