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