node.js 学习五 之 文件操作

node.js 中有同步读取文件和异步读取文件的区别

同步读取就是顺序进行,文件读取操作不进行完就不进行下一步操作
异步读取就是文件读取操作时,另起了一个线程,继续进行

异步的方法函数最后一个参数为回调函数,回调函数的第一个参数包含了错误信息(error)。

文件读取

05_readfile.js

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此访问
        console.log('访问');
        response.write('hello,world');
        var path = "D:\\learn\\nodejs\\05\\models\\test.txt"
        // optfile.readfile(path);
        optfile.readfileSync(path);
        response.end('hell,世界'); //不写则没有http协议尾
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');

./models/optfile.js

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

输出:
同步:

readfile.png

异步:


readfile_sync.png

使用闭包异步读取文件后写到前端

05_readfile.js

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('hell,世界')
        }

        console.log('访问');
        response.write('hello,world');
        var path = "D:\\learn\\nodejs\\05\\models\\test.txt"
        optfile.readfile(path, recall);
        // optfile.readfileSync(path);

        // response.end('hell,世界'); //不写则没有http协议尾
    }
}).listen(8000);
console.log('Server  running  at  http://127.0.0.1:8000/');

./models/optfile.js

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

你可能感兴趣的:(node.js 学习五 之 文件操作)