直接上源码了,用了ES6的语法:
'use strict';
const http = require('http');
var fs = require('fs');
http.get('http://img11.360buyimg.com/n1/jfs/t3451/90/758861696/258163/b95752c/58130f31Nb8582cd3.jpg', function (req, res) {
let bufferList = [];
let bufferLength = 0;
req.on('error', (error) => {
console.log(error);
});
req.on('data', function (data) {
bufferList.push(data);
bufferLength += data.length;
});
req.on('end', function (data) {
// 封面请求完成
let imgBuffer = new Buffer(bufferLength);
let pos = 0;
for (let buffer of bufferList) {
buffer.copy(imgBuffer, pos);
pos += buffer.length;
}
let test = `
<html>
<body>
<img src="data:image/jpg;base64,${imgBuffer.toString('base64')}" />
</body>
</html>
`;
fs.writeFileSync('test.base64.html',test);
fs.writeFileSync('test.base64.jpg',imgBuffer);
});
});