node.jsmulterpkgcloud

NodeJS + Multer + PkgCloud: resize image before sending it to cloud


I'm searching for a way to resize an image (uploaded by a standard html form submit) before sending it to cloud (openstack, s3 or else).

I'm using NodeJS and 3 plugins: Multer (upload management), lwip (image resizing) and PkgCloud (transfert to cloud).

I'm able to handle the upload with multer, and I can write a new resized file in the server with lwip.

var fs = require('fs'),
    multer  = require('multer'),
    upload = multer({ dest: 'uploads/medias/' }),
    pkgcloud = require('pkgcloud'),
    client = pkgcloud.storage.createClient({/* some config */});

// "router" is an instance of a route from Express
router.post('/media/:id/image', upload.single('file'), function (req) {
    var lwip = require('lwip'),
        type = 'png',
        npath = req.file.path + '_150x150';

    // the file exists and the log shows information
    console.log(req.file);

    // open image
    lwip.open(req.file.path, type, function (err, image) {
        image.batch()
            .resize(150, 150)
            .writeFile(npath, type, function () {
                // remove raw file
                fs.unlink(req.file.path, function () {
                    // how do I send the new resized file to the pkgcloud client?
                });
            });
    });
});

But I'm missing something, and I can't find a way to send this new file to the cloud. I discovered a plugin which manage transfert between multer and a configured pkgcloud instance (multer-storage-pkgcloud), but I can't figure out how to resize the file before sending it to cloud.

Does anyone have an idea how to handle that?

Thanks


Solution

  • I found a way to do it, by simply create a stream from the file and pipe it with pkgcloud instance:

    var fstream = fs.createReadStream(path_to_file);
    fstream.pipe(client.upload({
        container: 'container-id',
        remote: 'remote-name'
    });
    

    Is missing in this code: all the success and error callbacks. But the idea is here.