nodejs 适合做文件服务器吗
一般可以选择nodejs来做静态文件服务器。具体参考如下:
assets放置网站的静态文件css,js,img等;common存放项目的配置文件和一些通用文件;server存放服务处理文件,将要创建的静态文件服务就是放在此目录中; tpl放置的是模板文件也就是网页文件。
文件的下载格式主要是由'Content-Type'的值决定的,要想下载的文件能够正常工作就应该正确的设置不同文件的'Content-Type'值。mimejs文件存放了一些常用mime值:
[javascript] view plain copy
exportsmime = {
"html" : "text/html",
"css" : "text/css",
"js" : "text/javascript",
"json" : "application/json",
"ico" : "image/x-icon",
"gif" : "image/gif",
"jpeg" : "image/jpeg",
"jpg" : "image/jpeg",
"png" : "image/png",
"pdf" : "application/pdf",
"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"
};
先来看serverjs和FServerjs的类容:
[javascript] view plain copy
// serverjs
var config = require('/common/config');
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var FServer = require('/server/FServer');
function index(){
var indexPath = configui + '/indexhtml';
fsexists(indexPath, function(exists){
if( !exists ) {
throw err;
} else {
fsreadFile(indexPath, function(err, data){
if (err) {
throw err;
} else {
function onRequest(req, res){
// 取得文件路径
var pathname = urlparse(requrl)pathname;
// 获取文件扩展名(包含前置)
var extname = pathextname( pathname );
var type = extnameslice(1);
// 获取下载文件在磁盘上的路径,
var realPath = configroot + pathname;
if ( extname === '' ) {
reswriteHead(200, {'Content-Type':'text/html'});
reswrite(data);
resend();
} else {
FServerfilesLoad(realPath, type, req, res);
}
}
httpcreateServer(onRequest)listen(configport);
}
})
}
})
}
exportsindex = index;
// FServerjs
var fs = require('fs');
var mime = require('/common/mime')mime;
function filesLoad(filePath, type, req, res){
fsexists(filePath, function(exists){
if ( !exists ) {
reswriteHead(404, {'Content-Type': 'text/plain'});
// reswrite();
resend();
} else {
fsreadFile(filePath, 'binary', function(err, file){
if ( err ) {
reswriteHead(500, {'Content-Type': 'text/plain'});
// reswrite();
resend();
} else {
reswriteHead(200, {'Content-Type': mime[type]});
reswrite(file, 'binary');
resend();
}
});
}
})
}
exportsfilesLoad = filesLoad;
上面引入了nodejs的内置模块http、fs、url、path,config和FServer是自定义模块,要读取文件首先要知道文件在磁盘上是否存在,还应当知道文件的类型才能达到想要的效果。运行程序可以发现css和javascript都下载正确,并且css效果在页面上正确渲染(javascript还没有写效果)
0条评论