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);
  • 输出结果

 

转载于:https://www.cnblogs.com/saintdingspage/p/11425439.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值