node搭建服务器
2024-08-31 17:50:59
创建简单的服务器,可以简单连接
var http = require("http");
var server = http.createServer();
server.on("request",function(req,res){
res.end("ok");
})
server.listen(3000);
console.log("running in 3000");
判断是文件夹还是文件
fs.stat("./08.html",function(err,stats){
if(stats.isDirectory()){
console.log("是文件夹");
}else if(stats.isFile()){
console.log("是文件");
}
})
判断文件
fs.access("./08.html",function(err){
if(err){
console.log("文件不存在");
throw err;
}
fs.readFile("./08.html",function(err,data){
if(err){
throw err;
}
console.log("文件存在");
res.end(data);
})
})
MIME支持
现在给客户端返回文件时,我们并没有指定Content-Type
头,虽然你可能发现访问文本或图片浏览器都可以正确显示出文字或图片,但这并不符合规范。任何包含实体主体(entity body)的响应都应在头部指明文件类型,否则浏览器无从得知类型时,就会自行猜测(从文件内容以及url中寻找可能的扩展名)。响应如指定了错误的类型也会导致内容的错乱显示,如明明返回的是一张jpeg
图片,却错误指定了header:'Content-Type': 'text/html'
,会收到一堆乱码。
var mime = {
'psd': 'application/x-photoshop',
'ppt': 'application/powerpoint',
'php': 'application/x-httpd-php',
'mp3': 'audio/mp3',
'jpg': 'image/jpeg',
'png': 'image/png',
'tiff': 'image/tiff',
'tif': 'image/tiff',
'css': 'text/css',
'html': 'text/html',
'htm': 'text/html',
'txt': 'text/plain',
'text': 'text/plain',
'qt': 'video/quicktime',
'mov': 'video/quicktime',
'avi': 'video/x-msvideo',
'movie': 'video/x-sgi-movie',
'doc': 'application/msword',
'word': 'application/msword',
'json': 'text/json'
}
服务器获取请求后可以对请求路径做出处理的几种方法
var path = require("path");
console.log(path.basename("/foo/bar/index.html"));//"index.html"
console.log(path.basename("/foo/bar/index"));//"index"
console.log(path.extname("/foo/bar/index.html"));//".html"
console.log(path.extname("/foo/bar/index.css"));//".css"
console.log(path.extname("/foo/bar/index"));//""
console.log(path.dirname('/foo/bar/baz/asdf/quux')); // 返回: '/foo/bar/baz/asdf'
最新文章
- eclipse导入android项目红叉和红色感叹号怎么解决
- I/O复用模型之epoll学习
- Microsoft 2013 新技术学习笔记 四
- poj 2553 The Bottom of a Graph
- OpenGL中的投影使用
- WPF AutoGeneratingColumn 绑定下拉框
- Mybatis 逆向工程
- Introduction to the Build Lifecycle
- 杭州电acm理工大舞台版
- wordpress建站过程1
- 摆脱printf的噩梦
- [Ms SQL] 基本創建、修改與刪除
- luogu2605 基站选址 (线段树优化dp)
- #define用法之一
- mac 命令行上传文件,mac tar.gz命令压缩
- Linux日志文件/var/log详解
- Linux内核同步 - classic RCU的实现
- MySQL This function has none of DETERMINISTIC, NO SQL...错误1418 的原因分析及解决方法
- web站点启用https (二)
- tensorflow中使用mnist数据集训练全连接神经网络-学习笔记
热门文章
- NodeJS学习笔记 进阶 (8)express+morgan实现日志记录(ok)
- 20180929 北京大学 人工智能实践:Tensorflow笔记01
- 參加北京bluemix云计算大会偶记
- js斐波那契数列求和
- cvBoostStartTraining, cvBoostNextWeakClassifier和 cvBoostEndTraining
- SQLServer2008 R2安装步骤
- legend---四、菜鸟教程css3里面有教你炫酷的按钮怎么做
- 智课雅思词汇---四、clos和cap和ced是什么意思
- js 判断对touch事件支持
- JAVA使用Gson解析json数据,实例