let http = require("http");
let fs = require("fs");
let contentType = {
"html":"text/html",
"css":"text/css",
"js":"application/x-javascript",
"jpg":"application/x-jpg",
"png":"application/x-png",
"json":"application/json",
"map":"application/map",
"swf":"application/x-shockwave-flash"
}
http.createServer(function(req,res){
let url = req.url==="/"?'/index.html':req.url;
let file = __dirname + url;
let file_content_type = url.split(".")[url.split(".").length-1];
fs.readFile(file,function(error,data){
if(error){
res.writeHead('200',{
"Content-type":`${contentType[file_content_type]};charset='utf-8'`
});
res.write('<h2>404页面未找到</h2>');
res.end();
}else{
res.writeHead('200',{
"Content-type":`${contentType[file_content_type]};charset='utf-8'`
});
res.write(data);
res.end();
}
})
}).listen("2222");
console.log("the server is listen in 127.0.0.1:2222")Content-type类型写的还不够完整~
当然node也有一些成型的插件供你使用
anywhere
npm install anywhere -g
目录下运行 anywhere 就可以了~