Nodejs:閉包函式
阿新 • • 發佈:2018-12-12
//-------------optfile.js------------------------- var fs = require('fs'); module.exports = { readfileSync: function (path) { //同步讀取 var data = fs.readFileSync(path, 'utf-8'); console.log(data); console.log("同步方法執行完畢"); return data; }, readfile1: function (path, res) { //非同步執行 fs.readFile(path, function (err, data) { if (err) { console.log(err); } else { console.log(data.toString()); res.write(data);//報錯 } }); console.log("非同步方法執行完畢"); }, readfile2: function (path, recall) { //非同步執行 fs.readFile(path, function (err, data) { if (err) { console.log("非同步執行error:" + err); recall("檔案不存在,非同步執行error:" + err); } else { console.log(data.toString()); recall(data); } }); console.log("===非同步方法執行完畢==="); }, }
//-----------n5_readfile----讀取檔案--------------------- /* * 單執行緒非同步 */ var http = require('http'); var optfile = require('./model/optfile1.js'); http.createServer(function (request, response) { response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); if (request.url !== "/favicon.ico") { //清除第2此訪問 console.log('訪問'); function recall(data) {//閉包函式、回撥函式 console.log(data.toString()); response.write(data); response.end(""); //不寫則沒有htpp協議尾 } //optfile.readfile1('./view/01.txt', response); //response.end("ok"); optfile.readfile2('./view/01.txt', recall); console.log("===主程式執行完畢===!"); } }).listen(8000); console.log('Server running at http://127.0.0.1:8000/');