本文实例讲述了Nodejs处理异常操作。分享给大家供大家参考,具体如下:
Exception.js
module.exports = { expfun: function(flag) { if(flag == 0) { throw '我是error'; } return "success"; } }
optfile.js
//-------------optfile.js------------------------- var fs = require('fs'); module.exports = { readfile: function (path, recall) { //异步执行 fs.readFile(path, function (err, data) { if (err) { console.log("异步执行error:" + err); recall("文件不存在,异步执行error:" + err);//异步处理异常 } else { //console.log(data.toString()); recall(data); } }); console.log("===异步方法执行完毕==="); }, readImg: function (path, res) { fs.readFile(path, 'binary', function (err, filedata) { if (err) { console.log(err); return; } else { console.log("输出文件"); res.write(filedata, 'binary'); res.end(); } }); } }
router.js
var optfile = require('../model/optfile2.js'); function getRecall(req, res) { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); function recall(data) { res.write(data); res.end(''); //不写则没有http协议尾 } return recall; } module.exports = { login: function (req, res) { recall = getRecall(req, res); optfile.readfile('./view/login.html', recall); }, showimg: function (req, res) { res.writeHead(200, { 'Content-Type': 'image/jpeg' }); optfile.readImg("./view/pig.png", res); } }
//-------------n9_exception.js--------------- /* 同步的捕获&&异步的捕获 */ var http = require('http'); var url = require('url'); var router = require('./model/router'); var exception = require('./model/Exception'); http.createServer(function (request, response) { if (request.url !== "/favicon.ico") { //清除第2此访问 pathname = url.parse(request.url).pathname; pathname = pathname.replace(/\//, ''); //替换掉前面的/ try { router[pathname](request, response); // data = exception.expfun(0); // response.write(data); // response.end(''); } catch (err) { console.log('捕获到异常=' + err); response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); response.write(err.toString()); response.end(''); } console.log("server执行完毕"); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/');
希望本文所述对大家nodejs程序设计有所帮助。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 群星《十二女声Ⅲ》[WAV/CUE/分轨][626.4MB]
- 陈百强.1993-离不开...纪念歌集2CD【华纳】【WAV+CUE】
- 于台烟.2003-爱自己【乾坤唱片】【WAV+CUE】
- 群星.2024-我们永远是我们电影原声带【乐禾发文化】【FLAC分轨】
- 【中国民乐】张维良《秋江夜泊》2004[FLAC+CUE]
- 明达年度发烧碟MasterSuperiorAudiophile2011[DSF]
- 明达年度发烧碟MasterSuperiorAudiophile2017[DSF]
- 翁立友.2008-恨孤单【大旗】【WAV+CUE】
- 群星.2009-Magic.Cover日粤精华3CD【环球】【WAV+CUE】
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]