本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答