node fs组件入门(配置默认路径)

新增文件夹和文件

var http=require("http");
//导入文件操作组件fs
var fs=require("fs");
var url=require("url");

http.createServer(function(req,res){
	//读取两次的原因是第一次先会读取网页的图标,所以这里判断若是读取图标的话直接return
	if(req.url=="/favicon.ico"){
		return;
	}
	//创建文件夹,第一个参数是文件夹名,第二个方法回调,err是布尔值,为true代表错误
	fs.mkdir("./status",function(err){
			if (err==true) {
				console.log(err)
			}else{
				//创建文件,第一个参数是文件名,第二个参数是内容,第三个参数是回调函数
				fs.writeFile("./status/text.txt","我是文本内容",function(err){
					if (err==true) {
						console.log(err);
					}else{
						console.log("创建文件成功");
					}
				})
			}
		})
	res.end();
}).listen(3000,"localhost");

读取文件

var http=require("http");
//导入文件操作组件fs
var fs=require("fs");
var url=require("url");

http.createServer(function(req,res){
	//读取两次的原因是第一次先会读取网页的图标,所以这里判断若是读取图标的话直接return
	if(req.url=="/favicon.ico"){
		return;
	}
	
	//先要处理中文乱码
	res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
	//读取文件
	//第一个参数是文件地址,第二个是回调方法(这里用箭头函数)
	fs.readFile("./status/text.txt",(err,data)=>{
		//判断是否能读取到文件,这里不能写==true,只能直接写err
		if (err) {
			console.log(err);
		}else{
			//读取txt文件是ASCII码所以要转成字符串
			//write有两个参数,第一个参数:是一个buffer 或 字符串,表示发送的内容
			//第二个参数:encoding来说明它的编码方式,默认utf-8
			res.write(data.toString());
		}
		//end只能出现一次
		res.end();
	});
}).listen(3000,"localhost");

默认路由配置(如:直接输入http://localhost:3000/    显示固定页面)
附带常用content-type http://tool.oschina.net/commons/

var http=require("http");
//导入文件操作组件fs
var fs=require("fs");
var url=require("url");
//导入读取url后缀组件path
var path=require("path");

http.createServer(function(req,res){
	//读取两次的原因是第一次先会读取网页的图标,所以这里判断若是读取图标的话直接return
	if(req.url=="/favicon.ico"){
		return;
	}
	//配置默认路由路径
	//用url组件解析请求获取 pathname内容
	var pathname=url.parse(req.url).pathname;
	console.log(pathname);
	//通过if else判断pathname的参数,并指向到对应文件
	//配置默认输入http://localhost:3000/ 指向到index.html
	if (pathname=="/") {
		pathname="/index.html"
	}
	//寻找对应文件(通过拼接)
	fs.readFile("./status"+pathname,function(err,data){
		if (err) {
			console.log("找不到文件");
			//指向到对应写好的404.html
			fs.readFile("status/404.html",function(err,data){
				if (err) {console.log("连404页面都找不到")}
				else{
					//必须设置格式才能显示html的内容,状态码是404哦!
					res.writeHead(404,{"Content-type":"text/html;charset=UTF-8"});
					//这里只能用end,用write暂时找不到方法解决
					res.end(data);
				}
			})//readFile(找404页面)
		} //if
		else{
			//有符合条件的文件
			console.log("找到符合条件的文件");
			//获取文件后缀名
			let extname=path.extname(pathname);
			let mine=getMIne(extname);
			//动态根据后缀设置对应的编码
			res.writeHead(200,{"Content-type":mine});
			//这个data是最外层,成功找到对应文件的data
			res.end(data);
		}
	})


}).listen(3000,"localhost");

//此方法用于判断文件后缀返回对应的格式
function getMIne(extname){
	//注意是有"."的
	switch (extname){
		case ".html":
		//读取的是网页
		return "text/html;charset=UTF-8";
		//图片
		case ".jpg":
		return "image/jpg";
		//这是css样式
		case "css":
		return "text/css";
		break;
	}
}

猜你喜欢

转载自blog.csdn.net/chijiajing/article/details/83183638
今日推荐