request的pipe方法的问题

 request(src).pipe(fs.createWriteStream('./img/'+img_filename));

如何知道图片已经写入成功?而不是连接成功?

阅读 19.5k
3 个回答
var fs = require('fs');
var request = require("request");

var src = "https://www.google.com.hk/images/srpr/logo3w.png";

var writeStream = fs.createWriteStream('image.png');
var readStream = request(src)
readStream.pipe(writeStream);
readStream.on('end', function(response) {
    console.log('文件写入成功');
    writeStream.end();
});

writeStream.on("finish", function() {
    console.log("ok");
});

自己运行去吧,有end,而且能正常监听,刚才的答案写的时候我没注意到你写的是request请求。同样request和fs.createReadStream一样返回一个readStream对象。readStream的end和writeStream的finish都可以kan。

监听 fs.createWriteStream 的 事件

正解:

const fs=require('fs');
const request=require('request');

var writeStream=fs.createWriteStream('./mo/'+'error.jpg',{autoClose:true})

request(src).pipe(writeStream);

writeStream.on('finish',function(){
    console.log('文件写入成功')
})
推荐问题
宣传栏