node.js(五)---- 读取图片

用的是   fs.readFile() 和 fs.readFileSync();

在操作图片时,需要将header设置为‘image/jpeg’,在获取和输出时,需要将encoding设置为'binary'

const fs = require('fs');

module.exports = {
    readImg: (path,fn) => {  //异步读取图片
        fs.readFile(path,'binary',(err,data)=>{
            if(err){
                console.log(err);
            }else {
                if(typeof fn === 'function'){
                    fn(data);
                }
            }
        });   //图片是转成二进制流传的
    },
    readImgSync : (path)=>{  //同步读取图片
        return fs.readFileSync(path,'binary');
    }
};

const read_img = require('./read_img');
const http = require('http');  //导入http
const hostname = '192.168.1.108';  //ip地址   随便写   如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址
const port = 3000;  //端口号
const server = http.createServer((req, res) => {   //创建一个server
    res.statusCode = 200;
    // res.setHeader('Content-type', 'text/plain;charset = utf-8');
    res.setHeader('Content-type', 'image/jpeg');  //打印图片时,需将Content-type 设置为image/jpeg
    if (req.url !== '/favicon.ico') {  //清除二次访问
        // res.write('12');   //在打印图片前插入字符串会导致图片的二进制流破坏,导致图片打印不出来
        // res.write(read_img.readImgSync('./img/demo.jpg'),'binary');
        read_img.readImg('./img/demo.jpg',(data)=>{
            res.write(data,'binary');
            res.end();
        });
        // res.end();   //用于关闭连接  同步就不需要
    }
});

server.listen(port, hostname, () => {  //监听server
    console.log(`服务器运行在http://${hostname}:${port}/`);
});


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值