国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Nodejs處理異常操作示例

2024-05-06 15:43:51
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 峨边| 盱眙县| 莲花县| 阿荣旗| 壤塘县| 汶川县| 印江| 临澧县| 荆门市| 鄂托克旗| 云梦县| 三台县| 镇坪县| 婺源县| 甘孜县| 花垣县| 双鸭山市| 仙桃市| 栖霞市| 若尔盖县| 自治县| 荣昌县| 琼海市| 十堰市| 霍林郭勒市| 乳源| 南安市| 宕昌县| 济南市| 仙桃市| 建瓯市| 新龙县| 红安县| 顺昌县| 凌源市| 玉龙| 黑河市| 江油市| 布拖县| 鄯善县| 屏东市|