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))就可以
请问一下哪里出错了
/q/10...