zoukankan      html  css  js  c++  java
  • 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);
    • 输出结果

  • 相关阅读:
    Tensor总结
    Tensorflow池化
    conda操作
    KS值计算
    supervisor实践
    npm/yarn实践
    nni 环境搭建
    阿里云个人邮箱配置
    Jinja2宏使用
    利用VS code 远程调试 docker 中的 dotnet 应用
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/11425439.html
Copyright © 2011-2022 走看看