Nodejs如何处理长尾词查询中的异常操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计320个文字,预计阅读时间需要2分钟。
Node.js 处理异常操作示例:
javascript创建一个名为 `Exception.js` 的模块,用于定义一个抛出异常的函数:
javascriptconst Exception={ expfun: function(flag) { if (flag===0) { throw '我是error'; } return success; }};
module.exports=Exception;
在另一个文件 `optfile.js` 中,使用这个模块并处理异常:
javascriptconst Exception=require('./Exception');
try { const result=Exception.expfun(0); console.log(result);} catch (error) { console.error(error);}
本文实例讲述了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(''); //不写则没有127.0.0.1:8000/');
希望本文所述对大家nodejs程序设计有所帮助。
本文共计320个文字,预计阅读时间需要2分钟。
Node.js 处理异常操作示例:
javascript创建一个名为 `Exception.js` 的模块,用于定义一个抛出异常的函数:
javascriptconst Exception={ expfun: function(flag) { if (flag===0) { throw '我是error'; } return success; }};
module.exports=Exception;
在另一个文件 `optfile.js` 中,使用这个模块并处理异常:
javascriptconst Exception=require('./Exception');
try { const result=Exception.expfun(0); console.log(result);} catch (error) { console.error(error);}
本文实例讲述了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(''); //不写则没有127.0.0.1:8000/');
希望本文所述对大家nodejs程序设计有所帮助。

