node 开启本地服务器
新建server.js文件
终端命令node server
server.js代码
var http = require('http');
var url = require('url');
var fs = require('fs'); //fs
var server = http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
// var realPath = "process_admin_20171009" + pathname;//所有文件都存在与resources目录下
var realPath = pathname;//所有文件都存在与resources目录下
console.log(realPath);
fs.exists(realPath, function (exists) {//判断文件是否存在
if (!exists) {
res.writeHead(404,{"Content-Type":"text/plain"});
res.write("404\nNot Found!\n");
res.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if(realPath.indexOf('.css') != -1){
res.writeHead(200, {
'Content-Type': 'text/css'
});
}
if(realPath.indexOf('.js') != -1){
res.writeHead(200, {
'Content-Type': 'application/javascript'
});
}
if(realPath.indexOf('.html') != -1){
res.writeHead(200, {
'Content-Type': 'text/html'
});
}
res.write(file, "binary");
res.end();
});
}
});
});
server.listen(8089);
console.log("静态资源服务器已启动");