- 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);
- 輸出結果