Node.js 文件(读和写)

一、读取文件

分为:同步读取、异步读取

(一)、定义

1、同步读取:假如我写了5行代码,然后运行,它是从第一行,第二行····第五行的运行方式,在第一行,读取完,第二行才能读取,按顺序读取,这个就是同步读取。

2、异步读取:假如我写了5行代码,然后运行,在第二行代码的时候,他去读取磁盘上的文件,在读取的过程中,它另起了一个线程,又去读取这个磁盘,这个时候,继续往下运行,到了第三行的时候,如果他想要第二行代码返回来的结果就会出现问题,这个就是异步读取。  

(二)、同步读取应用

1、创建 n5


2、写入

var  http  =  require('http');
var optfile = require('./models/optfile');
http.createServer(function  (request,  response)  {
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url!=="/favicon.ico"){  //清除第2此访问
	optfile.readfileSync('./views/login.html');
        response.end('=======');//不写则没有http协议尾
		
		console.log("主程序执行完毕");
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');

3、创建 optfile


4、内容

var  fs=  require('fs');
module.exports={
	readfileSync:function(path){      //同步读取
		//读路径
        var  data  =  fs.readFileSync(path,'utf-8');
        console.log(data);
        console.log("同步方法执行完毕");                
    },
    readfile:function(path){          //异步执行
        fs.readFile(path,  function  (err,  data)  {
            if  (err)  {
              console.log(err);
            }else{
              console.log(data.toString());
            }
        });
        console.log("异步方法执行完毕");
    }
}

5、创建  F:\node.js\study\views


6、写入

登录界面    四个字

7、运行



8、运行顺序:

现在n5中运行   optfile.readfileSync('./views/login.html');

转到optfile 运行

         var  data  =  fs.readFileSync(path,'utf-8');

到login.html 运行

        登录界面 =  console.log(data);

回到optfile运行

        console.log("同步方法执行完毕");

最后回到n5中

        response.end('=======');//不写则没有http协议尾
console.log("主程序执行完毕");

============================================================================

但是,node.js它的优势在于单线程异步。

所谓单线程,例如server服务端,有1万人进行访问的时候,排队:1,2,3,4,5,·······,10000。如果采用单线程同步的话,“1” 读取完(IO),才能轮到第二个访问;这就会使性能下降。那么这个时候它采用异步的方式,把这些比较消耗性能的,放到异步里面去操作,直接操作到底,使性能增强。

(三)、异步读取应用

1、n5

var  http  =  require('http');
var optfile = require('./models/optfile');
http.createServer(function  (request,  response)  {
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url!=="/favicon.ico"){  //清除第2此访问
		function recall(data ){
			response.write(data);
			response.end('okkkkkkk');//不写则没有http协议尾
		}
		optfile.readfile('./views/login.html',recall);
        
		console.log("主程序执行完毕");
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');

2、optfile

var  fs=  require('fs');
module.exports={
	readfileSync:function(path){      //同步读取
		//读路径
        var  data  =  fs.readFileSync(path,'utf-8');
        console.log(data);
        console.log("同步方法执行完毕");                
    },
    readfile:function(path,recall){          //异步执行
        fs.readFile(path,  function  (err,  data)  {
			//如果错误err
            if  (err)  {
              console.log(err);
            }else{
              console.log(data.toString());
	      recall(data);
            }
        });
        console.log("异步方法执行完毕");
    }
}

3、运行



============================================================================

(四)、用路由读取不同的界面

1、luyou1.js

var optfile = require('./models/optfile');
//声明函数集
module.exports={
    login:function(req,res){
        function recall(data ){
			res.write(data);
			res.end('');//不写则没有http协议尾
		}
		optfile.readfile('./views/login.html',recall);
    },
    setin:function(req,res){
		function recall(data ){
			res.write(data);
			res.end('');//不写则没有http协议尾
		}
		optfile.readfile('./views/setin.html',recall);
    }
}

2、n5

var  http  =  require('http');
var    url    =    require('url');
var    luyou    =    require('./luyou');
http.createServer(function  (request,  response)  {
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url!=="/favicon.ico"){  //清除第2此访问
	var pathname = url.parse(request.url).pathname;
	pathname = pathname.replace(/\//, '');//替换掉前面的/ ,变成空字符串
	luyou[pathname](request,response);
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');

3、F:\node.js\study\views


写入注册界面

4、运行



==========================================================================

二、写文件

两种操作:同步写文件、异步写文件

(一)、异步写文件

1、optfile中
var  fs=  require('fs');
module.exports={
	readfileSync:function(path){      //同步读取
		//读路径
        var  data  =  fs.readFileSync(path,'utf-8');
        console.log(data);
        console.log("同步方法执行完毕");                
    },
    readfile:function(path,recall){          //异步执行
        fs.readFile(path,  function  (err,  data)  {
			//如果错误err
            if  (err)  {
              console.log(err);
            }else{
              console.log(data.toString());
			  recall(data);
            }
        });
        console.log("异步方法执行完毕");
    },
	//加入以下代码
    writefile:function(path,data,recall){    //异步方式
        fs.writeFile(path,  data,  function  (err)  {
            if  (err)  {
                throw  err;
            }
            console.log('It\'s  saved!');  //文件被保存
			recall('写文件成功!');
          });
    },
    writeFileSync:function(path,data){  //同步方式
        fs.writeFileSync(path,  data);
        console.log("同步写文件完成");
    }
}
2、luyou
var optfile = require('./models/optfile');
//声明函数集
module.exports={
    login:function(req,res){
        function recall(data ){
			res.write(data);
			res.end('');//不写则没有http协议尾
		}
		optfile.readfile('./views/login.html',recall);
    },
    setin:function(req,res){
		function recall(data ){
			res.write(data);
			res.end('');//不写则没有http协议尾
		}
		optfile.readfile('./views/setin.html',recall);
    },
    writefile:function(req ,res){
		function recall(data ){
			res.write(data);
			res.end('');//不写则没有http协议尾
		}
		optfile.writefile('./views/one.text','天气好好!!!',recall);
	}
}
3、n6


var  http  =  require('http');
var    url    =    require('url');
var    luyou    =    require('./luyou');
http.createServer(function  (request,  response)  {
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url!=="/favicon.ico"){  //清除第2此访问
		var pathname = url.parse(request.url).pathname;
		pathname = pathname.replace(/\//, '');//替换掉前面的/ ,变成空字符串
		luyou[pathname](request,response);
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');
4、运行




打开文件:


猜你喜欢

转载自blog.csdn.net/qq_28289405/article/details/80606549