我正在尝试使用nodejs,request和gm模块下载图像后立即调整图像大小但是我很难理解管道内容。
var fs = require('fs');
var path = require('path');
var gm = require('gm').subClass({imageMagick: true});
var request = require('request');
var async = require('async');
var folderImages = './images/';
var q = async.queue(function (task, callback) {
// Renaming the images
var thumb350 = task.target.replace('.jpg', '-350.jpg');
// The target path/images
var target350 = path.join(folderImages, thumb350);
// Download the images
request
.get(task.PhotoURL)
.on('response', function(response) {
console.log(task.PhotoURL + ' : ' + response.statusCode, response.headers['content-type']);
callback();
})
.on('error', function(err) {
console.log(err);
callback(err);
})
.pipe(fs.createWriteStream(task.target));
// How can I run this function on files that get downloaded?
var resizePhotos = gm(task.target)
.resize('350')
.write(target350, function (err) {
if (!err){
console.log(task.target, ': 350 done');
}
else {
console.log(task.target, ': error');
}
});
}, 50);
答案 0 :(得分:0)
您可以在writeStream上侦听finish
事件,然后在回调中调整大小调整逻辑:
...
.pipe(fs.createWriteStream(task.target))
.on('finish', function(){
//called when writing to disk is complete
var resizePhotos = gm(task.target)
.resize('350')
.write(target350, function (err) {
if (!err){
console.log(task.target, ': 350 done');
}
else {
console.log(task.target, ': error');
}
});
})
答案 1 :(得分:0)
实际上request.get
会返回一个流,您只需gm(request.get(url)).resize(350)
而不是写入文件系统并重新加载它。