摘要:本文介绍了Node.js写文件的三种方法,分别为:通过管道流写文件、手动管理流写入和通过一次性读完数据写入,希望对大家学习Node.js有所帮助。
1、通过管道流写文件
采用管道传输二进制流,可以实现自动管理流,可写流不必当心可读流流的过快而崩溃,适合大小文件传输(推荐)
var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); // 必须解码url readStream.pipe(res); // 管道传输 res.writeHead(200,{ 'Content-Type' : contType }); // 出错处理 readStream.on('error', function() { res.writeHead(404,'can not find this page',{ 'Content-Type' : 'text/html' }); readStream.pause(); res.end('404 can not find this page'); console.log('error in writing or reading '); });
2、手动管理流写入
手动管理流,适合大小文件的处理
var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); res.writeHead(200,{ 'Content-Type' : contType 4 }); // 当有数据可读时,触发该函数,chunk为所读取到的块 readStream.on('data',function(chunk) { res.write(chunk); }); // 出错时的处理 readStream.on('error', function() { res.writeHead(404,'can not find this page',{ 'Content-Type' : 'text/html' }); readStream.pause(); res.end('404 can not find this page'); console.log('error in writing or reading '); }); // 数据读取完毕 readStream.on('end',function() { res.end(); });
3、通过一次性读完数据写入
一次性读取完文件所有内容,适合小文件(不推荐)
fs.readFile(decodeURIComponent(root + filepath.pathname), function(err, data) { if(err) { res.writeHead(404,'can not find this page',{ 'Content-Type' : 'text/html' }); res.write('404 can not find this page'); }else { res.writeHead(200,{ 'Content-Type' : contType }); res.write(data); } res.end(); });
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号