Nodejs學習筆記-讀取顯示圖片

weixin_33860722發表於2017-10-24

程式碼:https://github.com/fengchunjian/nodejs_examples/tree/master/routerv4

// vim models/optfile.js
var fs = require('fs')
module.exports = {
    readImg : function(path, res) {
        fs.readFile(path, "binary", function(err, file) {
            if (err) {
                console.log(err);
                return;
            } else {
                console.log("讀取圖片完成");
                res.writeHead(200,  {'Content-Type':'image/jpeg'});
                res.write(file, "binary");
                res.end();
            }
        });
    },
    writefile : function(path, data, recall) {
        fs.writeFile(path, data, function(err) {
            if (err) {
                throw err;
            }
            console.log("非同步寫檔案完成");
            recall("非同步寫檔案完成");
        });
    },
    writefileSync : function(path, data, res) {
        fs.writeFileSync(path, data);
        console.log("同步寫檔案完成");
        res.write("同步寫檔案完成");
    },
    readfile : function(path, recall) {
        fs.readFile(path, function(err, data) {
            if (err) {
                console.log(err);
            } else {
                recall(data);
            }
        });
        console.log("非同步方法執行完畢");
    },
    readfileSync : function(path, res) {
        var data = fs.readFileSync(path, "utf-8");
        console.log(data);
        console.log("同步方法執行完畢");
        res.write(data);
    }
}
//vim models/router.js
var optfile = require("./optfile");
module.exports = {
    readImg : function(path, res) {
        optfile.readImg("./imgs/nodejs.jpg", res);
    },
    writefile : function(req, res) {
        function recall(data) {
            res.write(data);
            res.end();
        }
        optfile.writefile("./file.txt", "非同步檔案寫入", recall);
    },
    writefileSync : function(req, res) {
        optfile.writefileSync("./sync.txt", "同步檔案寫入", res);
        res.end();
    },
    login : function(req, res) {
        function recall(data) {
            res.write(data);
            res.end();
        }
        optfile.readfile("./views/login.html", recall);
    },
    zhuce : function(req, res) {
        function recall(data) {
            res.write(data);
            res.end();
        }
        optfile.readfile("./views/zhuce.html", recall);
    }
}
\\vim routercall.js
var url = require('url');
var router = require('./models/router');
http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    pathname = pathname.replace(/\//, '');
    router[pathname](request, response);
    console.log("主程式執行完畢");
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

node routercall.js
Server running at http://127.0.0.1:8000/
主程式執行完畢
讀取圖片完成

http://localhost:8000/readImg

相關文章