Cnodejs.org 위의 정적 서버 예제를 참조하면 캐시 및 압축이 포함 된 다음 Nodejs STATIC SERVER 예제를 작성했으며 코드는 다음과 같습니다.
코드 사본은 다음과 같습니다.
/**
* 정적 파일 서버 테스트 예제
* 사용자 : XUWM
* 날짜 : 13-5-17
* 시간 : 오전 8시 38 분
*이 템플릿을 변경하려면 파일 사용 | 설정 | 파일 템플릿.
*/
var port = 3333;
var http = 요구 사항 ( "http");
var url = require ( "url");
var fs = 요구 ( "fs");
var path = 요구 ( "경로");
var mime = 요구 사항 ( "./ mime"). 유형;
var config = require ( "./ config");
var zlib = 요구 사항 ( "zlib");
// HTTP 서버를 만듭니다
var server = http.createserver (함수 (요청, 응답) {
var obj = url.parse (request.url);
Response.SetHeader ( "Server", "Node/V8");
Console.log (OBJ);
var pathname = obj.pathname;
if (pathname.slice (-1) === "/") {
pathname = pathname+config.welcome.file; // default Index.html은 현재 기본값에서 선택됩니다
}
var realpath = path.join ( "자산", path.normanize (pathname.replace (//././ g, ""));
Console.log (RealPath);
var pathhandle = function (realPath) {
// fs.stat 메소드를 사용하여 파일을 가져옵니다
fs.stat (realpath, function (err, stats) {
if (err) {
response.writehead (404, "찾을 수 없음", { 'content-type': 'text/plain'});
response.write ( "요청"+realPath+"는 찾을 수 없습니다");
응답 ();
}또 다른{
if (stats.isdirectory ()) {
}또 다른{
var ext = path.extname (realpath);
ext = ext? ext.slice (1) : '알 수없는';
var contenttype = mime [ext] || "텍스트/평원";
Response.SetHeader ( "Content-Type", ContentType);
var lastmodified = stats.mtime.toutcstring ();
var ifmodifiedsince = "if-modified-since".tolowercase ();
Response.SetHeader ( "최후의 수정", 최종 변형);
if (ext.match (config.expires.filematch)) {
var 만료 = 새 날짜 ();
Expires.settime (lepires.gettime () + config.expires.maxage * 1000);
Response.SetHeader ( "만료", 만료 .toutCstring ());
response.setHeader ( "캐시 제어", "max-age =" + config.expires.maxage);
}
if (request.headers [ifModifiedSince] && lastModified == request.headers [ifModifiedSince]) {
console.log ( "브라우저 캐시에서 가져 오기")
Response.WriteHead (304, "수정되지 않음");
응답 ();
} 또 다른 {
var raw = fs.createreadstream (RealPath);
var acceptencoding = request.headers [ 'accept-encoding'] || "";;
var matched = ext.match (config.compress.match);
if (matched && acceptencoding.match (// bgzip/b/)) {
response.writehead (200, "OK", { 'Content-Encoding': 'gzip'});
raw.pipe (zlib.creategzip ()). 파이프 (응답);
} else if (matched && acceptencoding.match (// bdeflate/b/)) {
response.writehead (200, "OK", { 'Content-Encoding': 'deflate'});
raw.pipe (zlib.createdeflate ()). 파이프 (응답);
} 또 다른 {
응답 .WriteHead (200, "OK");
raw.pipe (응답);
}
}
}
}
});
}
Pathhandle (RealPath);
});
Server.Listen (포트);
Console.log ( "포트에서 실행되는 HTTP 서버 :"+포트);
먼저 JS 파일에 자산 폴더를 생성하고 INDEX.HTML, DEMO.JS 등과 같이 찾아 볼 정적 파일을 넣어야합니다.
실행 메소드는 : 위의 JS 파일 디렉토리로 전환 한 다음 노드 js 파일 이름을 입력합니다.
브라우저에 http : // localhost : 3333/를 입력하여 효과를 확인하십시오.
-위 코드에서 누락 된 두 모듈에서 채우십시오.
mime.js
코드 사본은 다음과 같습니다.
내보내기. 타입 = {
"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": "이미지/SVG+XML",
"SWF": "Application/X-Shockwave-Flash",
"Tiff": "Image/Tiff",
"txt": "Text/Plain",
"Wav": "Audio/X-Wav",
"WMA": "Audio/X-MS-WMA",
"WMV": "비디오/X-MS-WMV",
"XML": "Text/XML"
};
config.js
코드 사본은 다음과 같습니다.
Exports.expires = {
filematch : /^(gif | png | jpg | js | css) $ /ig,
최대 : 60 * 60 * 24 * 365
};
Exports.compress = {
일치 : /css | js | html /ig
};
Exports.welcome = {
파일 : "index.html"
};