项目在node本地服务器上运行

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端口上的

网址输入:该项目就可以运行了

 

 

 我的项目的文件夹:

 

posted @ 2018-11-16 17:33  苏小白啊  阅读(2697)  评论(0编辑  收藏  举报