使用节点根据请求提供调整大小的图像的问题

Issue with delivering a resized image on request with node

我用的是sailsjs,网站是sailsjs.org.

我想创建一个控制器函数,以便在请求图像时可以调整图像大小并在访问者第一次请求图像时将其缓存,然后在访问者下次请求时从缓存中检索。

我已经设置了到资产控制器的路由:

'get /image/:width/:height/:image': {
    controller: 'AssetController',
    action: 'image'
},

我已经设置了一个策略来拦截来自上述路由的图像请求并将文件调整大小/将文件保存到缓存中:

var fs = require('fs'),
im = require('imagemagick');

module.exports = function imageCacheResize(req, res, next){
    var width = req.param('width');
    var height = req.param('height');
    var file = req.param('image');

    if(width && height){

        //read from cache
        dir = 'assets/images/uploads/cache/'+width+'X'+height+'/';
        filename = dir+file;
        if (!fs.existsSync(dir)){
            fs.mkdirSync(dir);
        }
        if(!fs.exists(filename)){
            //write to file if not exist
            var originalFile = 'assets/images/uploads/'+file;

            im.resize({
                srcPath: originalFile,
                dstPath: filename,
                width:   width
            }, function(err, stdout, stderr){
                if (err) throw err;
            });
        }
    }
    next();
};

我还有一个 action/function 控制器设置来处理 return 调整大小的图像:

image: function(req, res){
    var file = req.param('image');
    var filename = 'assets/images/uploads/'+file;

    if((typeof req.param('width') != 'undefined')
        &&(typeof req.param('height') != 'undefined'))
    {
        var width = req.param('width');
        var height = req.param('height');
    }
    if(typeof req.param('size') != 'undefined'){
        var size = req.param('size');
    }

    if(width && height){


        //read from cache
        dir = 'assets/images/uploads/cache/'+width+'X'+height+'/';
        file = dir+file;
    }else{
        file = 'assets/images/uploads/'+file;
    }
    console.log(file);
    res.sendfile(file);
}

所有代码都能正常工作并创建然后保存调整大小的图像,但是它不会 return 第一次请求时的图像,但它会在第二次请求时。

原来我没有将 next() 命令放在正确的位置。似乎在等待图像调整大小时,代码继续并命中最终的 next()。

我已将图像调整大小策略更改为:

var fs = require('fs'),
im = require('imagemagick');

module.exports = function imageCacheResize(req, res, next){
var width = req.param('width');
var height = req.param('height');
var file = req.param('image');

if(width && height){

    //read from cache
    dir = 'assets/images/uploads/cache/'+width+'X'+height+'/';
    filename = dir+file;
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
    if(!fs.exists(filename)){
        //write to file if not exist
        var originalFile = 'assets/images/uploads/'+file;

        im.resize({
            srcPath: originalFile,
            dstPath: filename,
            width:   width
        }, function(err, stdout, stderr){
            if (err) throw err;
            next();
        });
    }else{
        next();
    }
}else{
    next();
}
};