const koa = require('koa');
const request = require('request');
const fs = require('fs');
const path = require('path');
function requestAsync(url) {
return new Promise((resolve, reject) => {
request({
url: url
}, (err, res, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
})
});
}
function writeFileAsync(path, data, option) {
return new Promise((resolve, reject) => {
fs.writeFile(path, data, option, (err)=> {
if (err) {
reject(err);
} else {
resolve();
}
})
});
}
const app = new koa();
app.use(async (ctx) => {
let url = 'http://pubimage.360doc.com/index7/bannerl_1.jpg';
let filepath = path.join(__dirname, './images/详情');
filepath = filepath + '/1.jpg';
// request(url).pipe(fs.createWriteStream(filepath));这个可以正常抓取图片
let data = await requestAsync(url);
let buffer = Buffer.from(data);
await writeFileAsync(filepath, buffer);
ctx.type = 'jpg';
ctx.body = buffer;
})
app.listen(3000);
console.log(`starting at ${3000}`);
我把request 和 writefile 都寫成了promise的形式,抓取html是可以的,抓取圖片就不行了
一開始data 輸出是string類型,也就是request 的body是string類型,我就使用Buffer.from
轉為buffer類型,也是不行,改為Buffer.from(data, 'base64')也是不行,但就是使用request(url).pipe(fs.createWriteStream(filepath))就可以
請問一下哪裡出錯了