关于抓取图片时候遇到的错误 Unhandled stream error in pipe. - CNode技术社区

关于抓取图片时候遇到的错误 Unhandled stream error in pipe.
发布于 12 年前 作者 whatispython 13397 次浏览 最后一次编辑是 9 年前

在批量抓取图片的时候,总是会出现如题所示的错误,请有经验的同学指点一二,核心代码如下:

request(searchUrl, function(err, res, body) {
 if (!err && res.statusCode == 200) {
 var images,
 imageUrl,
 imageName,
 timestamp = new Date().getTime();
 
 mkdirp(filePath);
 $ = cheerio.load(body);
 images = $('.box img');
 images.each(function(i, e) {
 imageUrl = e.attribs['src'].replace(/\/t\//, '/pre/');
 imageName = timestamp + i + '.jpg';
 console.log(imageUrl);
 request(imageUrl).pipe(fs.createWriteStream(filePath + "/" + imageName));
 }); 
 }
}); 
6 回复

我也碰上了。用pipe的时候就容易报错。后来改成这么写就没问题了
<pre> request({uri: imgSrc, encoding: ‘binary’}, function (error, response, body) { if (!error && response.statusCode == 200) { fs.writeFile(dest, body, ‘binary’, function (err) { if (err) {console.log(err);} }); } }); </pre>

我对node理解也不深,还是希望其他人能解释下pipe出错的原因

http://isawsomecode.tumblr.com/post/24371068694/fs-createreadstream-should-be-re-engineered 会不会是这种原因。 在fs.createWriteStream的时候on一下error呢。

确实在https://github.com/joyent/node/blob/master/lib/stream.js 代码的 90 〜 97行:

// don't leave dangling pipes when there are errors.
 function onerror(er) {
 cleanup();
 if (EE.listenerCount(this, 'error') === 0) {
 throw er; // Unhandled stream error in pipe.
 }
 }

不考虑因为这是网络问题导致的?

把 on(‘error’, fn) 放在 pipe 之前,才能捕捉到 pipe 的错误

回到顶部

AltStyle によって変換されたページ (->オリジナル) /