用的是 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}/`); });