node.js通过回调函数获取异步函数的返回结果


  • html文件代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的node.js首页</title>
</head>
<body>

</body>
</html>
  • 通过buffer流读取html文件
var fs = require('fs'); function wuwa(callback) { fs.open('.././webpage/firstpage.html','r',function (err,fd) { var readbyte = Buffer.alloc(1024); var offset = 0; var len = readbyte.length; var readposition = null; function saiwa(callback) { fs.read(fd, readbyte, offset, len, readposition, function (err, readBytes) { if (err) throw new err('~oh,no'); //console.log(readbyte.slice(0, readBytes).toString('utf8'));
                var  ret = readbyte.slice(0, readBytes).toString('utf8'); callback(ret); }) } saiwa(function (data) { callback(data) }) }) } module.exports = wuwa;
  • 新建一个文件调取buffer读取定义好的函数
var weirwa=require('./readwebpage'); console.log(weirwa); weirwa(function (data) { console.log(data); });

输出结果:

[Function: wuwa] <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的node.js首页</title>
</head>
<body>

</body>
</html> Process finished with exit code 0
  •  创建server返回结果
var http = require('http'); var url = require('url'); var weirwa=require('./readwebpage'); http.createServer(function (req,res) { res.writeHead(200,{'content-Type':'text/plain; charset=UTF-8'}); weirwa(function (data) { res.end(data); }); console.log("url: "+url.parse(req.url)); }).listen(3000);
  • 输出结果

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM