Nodejs 学习(三)--文件操作

1.文件的读取(同步与异步)

对文件的读写需要导入标准模块fsvar fs = require('fs'), 我们将读取文件的函数都写到一个文件里optfile.js
同步读取:调用fs的readFileSync函数

//----------------------optfile.js----------------
var fs = require('fs')
module.exports = {
    readfileSync:function(path) {//同步读取
        var data = fs.readFileSync(path, 'utf-8');
        return data
    }
}

异步读取:调用fs的readFile函数, 这里需要注意, readFile为异步方法, 参数中绑定了回调函数并自动实现了异常处理。

//----------------------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)
            }
        });
    }

}

所以在引入optfile.js文件后, 在主函数中可以分别调用上面两种函数读取文件。这里还需要注意的一点是,读取文件的路径是相对于主函数所在文件路径还是具体读取文件函数文件路径, 这里应该是主函数所在文件路径, 因为引入optfile后, 文件中的函数代码就相当于嵌入主函数文件中。

var http = require('http');
var optfile = require('./models/optfile')
http.createServer(function(request, response) {
        optfile.readfileSync('./views/login.html');     //同步读取
        optfile.readfile('./views/login.html');     //异步读取
        response.end()
        console.log('主程序执行完毕')


}).listen(80);
console.log('Server is running at 127.0.1.1:80')

读取文件之后如果我们想要将读取内容输出到前段(一般读取前段模板文件然后在前端显示)我们可以在读取文件的函数中传入response作为参数, 然后通过response将内容在前端显示。这种方法在同步过程中没有问题。 但是这里需要注意的是在异步调用中, 要讲response.write()和response.end()都写在回调函数中, 这样可以保证end在write之后, 否则程序会出错。 我们也可以利用闭包,即在主函数中再声明一个函数recall, 将recall作为参数传入readfile方法中,在readfile方法中调用recall。 由于闭包函数特性, recall方法保持了主函数的request和response变量。 所以可以在readfile方法中对response进行处理

var http = require('http');
var optfile = require('./models/optfile')
http.createServer(function(request, response) {
        response.writeHead(200,{"Content-Type":"text/thml, charset=utf-8"});
        function recall(data) {
            response.write(data.toString())
            response.end()
        }
        optfile.readfile('./views/login.html',recall);  

        console.log('主程序执行完毕')


}).listen(80);
console.log('Server is running at 127.0.1.1:80')

相应的optfile.js中的readfile函数改写为

readfile:function(path, recall) {//异步方法
        fs.readFile(path,function(err, data) {
            if(err) {
                console.log(err)
            }else {
                recall(data)//调用recall
            }
        })
    }

2.改写router
我们希望访问不同的路由, 得到不同的html页面, 所以可以将路由和文件读取相结合实现

//-----------router.js-------------------
var optfile = require('./models/optfile')
module.exports = {
    login:function(req, res) {
        function recall(data) {
            res.write(data.toString())
            res.end()
        }
    optfile.readfile('./views/login.html', recall)

    }, 
    register:function(req, res) {
        function recall(data) {
            res.write(data.toString())
            res.end()
        }
    optfile.readfile('./views/register.html', recall)
    }
}

主函数文件为

var http = require('http');
var url = require('url')
var router=require('./router.js')
http.createServer(function(request, response) {

        response.writeHead(200,{"Content-Type":"text/html, charset=utf-8"});
        var pathname = url.parse(request.url).pathname;
        pathname = pathname.replace(/\//,'');
        try{
            router[pathname](request, response);    
        }catch (err) {
            response.write(err.toString())
            response.end()
        }

        console.log('主程序执行完毕')

}).listen(80);
console.log('Server is running at 127.0.1.1:80')

3.文件写入(同步与异步)

文件写入与上面的文件读取类似,直接上代码
同步写入

writefileSync:function(path, data) {
    fs.writeFileSync(path,  data);
        console.log("同步写文件完成");
    },

异步写入

writefile:function(path, data) {
    fs.writeFile(path, data, function (err){
        if (err) {
            throw err
        }
        console.log('异步写文件完成')
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值