参考文章:3分钟快速搭建nodejs本地服务器运行测试html/js
首先确认你已经安装了node.js,没有的话请先下载安装 node.js
第1步:在你的项目文件夹的根目录里新建 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("page", 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 {
// 这里很重要,你的各种资源一定要设置对应的 MIME 类型(这里使用单独的mine文件)
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步,新建一个资源类型文件,用来返回正确的content-type
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步,确认你的页面以及资源文件放入了正确的文件夹
上面的http.js里面写了 “page” 作为网页存放目录,所以要把你的index.html等文件都放入 “page” 文件夹内
第4步, 在你的项目根目录下启动控制台(git bash),输入启动命令后,打开浏览器输入控制台打印出来的地址即可访问 (http://localhost:3000/index.html)
node http.js
一般是在浏览器里输入:
http://localhost:3000/index.html