欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Nodejs處理異常操作示例

 更新時間:2018年12月25日 09:06:46   作者:ChouCat  
這篇文章主要介紹了Nodejs處理異常操作,結(jié)合實例形式分析了nodejs針對異常的捕獲與處理相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了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) { //異步執(zhí)行
    fs.readFile(path, function (err, data) {
      if (err) {
        console.log("異步執(zhí)行error:" + err);
        recall("文件不存在,異步執(zhí)行error:" + err);//異步處理異常
      } else {
        //console.log(data.toString());
        recall(data);
      }
    });
    console.log("===異步方法執(zhí)行完畢===");
  },
  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協(xié)議尾
  }
  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執(zhí)行完畢");
  }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

希望本文所述對大家nodejs程序設(shè)計有所幫助。

相關(guān)文章

最新評論