Nodejs处理异常操作示例

  

本文实例讲述了Nodejs处理异常操作。分享给大家供大家参考,具体如下:

  

<强> Exception.js

        模块。出口={   expfun:函数(国旗){   如果(标志==0){   把“我是错误的;   }   返回“成功”;   }   }      之前      

<强> optfile.js

     //- - - - - - - - - - - - -optfile.js - - - - - - - - - - - - - - - - - - - - - - - - -   var fs=要求(fs);   模块。出口={   readfile:函数(路径,召回){//异步执行   fs。readFile函数的路径,(呃,数据){   如果(err) {   控制台。日志(“异步执行错误:“+错);   回忆(“文件不存在,异步执行错误:“+犯错);//异步处理异常   其他}{//console.log (data.toString ());   回忆(数据);   }   });   console.log(“===异步方法执行完毕===");   },   readImg:函数(路径,res) {   fs。readFile函数的路径、“二进制”(呃,filedata) {   如果(err) {   console.log(错);   返回;   其他}{   console.log(“输出文件”);   res.write (filedata“二进制”);   res.end ();   }   });   }   }      之前      

<强> router.js

        var optfile=要求(“. ./模型/optfile2.js”);   函数getRecall(点播,res) {   res.writeHead(200年,{   “内容类型”:“text/html;charset=utf - 8 '   });   函数召回(数据){   res.write(数据);   res.end (");//不写则没有http协议尾   }   返回召回;   }   模块。出口={   登录:函数(点播,res) {   回忆=getRecall(点播,res);   optfile.readfile('/视图/登录。html的,回忆);   },   res showimg:函数(点播){   res.writeHead(200年,{   ”image/jpeg”“内容类型”:   });   optfile.readImg(“/视图/猪。png”, res);   }   }      之前      

  //- - - - - - - - - - - - -n9_exception.js - - - - - - - - - - - - - - - - - -/*   同步的捕获,和异步的捕获   */var http=要求(“http”);   var url=要求(url);   var路由器=要求(“。/模型/路由器”);   var=异常需要('/模型/例外。');   http。createServer(函数(请求、响应){   如果请求。url !=="/ico”位于){//清除第2此访问   路径名=url.parse (request.url) .pathname;   路径名=路径名。替换(/\//?;//替换掉前面的/尝试{   路由器(路径名)(请求、响应);//数据=https://www.yisu.com/zixun/exception.expfun (0);//response.write(数据);//response.end (");   }捕捉(err) {   控制台。日志(“捕获到异常=' +错);   响应。writeHead(200年,{   “内容类型”:“text/html;charset=utf - 8 '   });   response.write (err.toString ());   response.end (");   }   console.log(“服务器执行完毕”);   }   }).listen (8000);   控制台。日志(服务器运行在http://127.0.0.1:8000);   

  

希望本文所述对大家nodejs程序设计有所帮助。

Nodejs处理异常操作示例