Search code examples
javascriptnode.jsexpressimage-optimization

Image optimization on the server using node


I have a server that's uploading images to the server. I need to optimize the image upload somehow. This is how I'm uploading my files:

uploadImage(file, uid, res) {
    var fs = require('fs');
    mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
    var conn = mongoose.connection;
    Grid.mongo = mongoose.mongo;
    const gfs = Grid(conn.db);
    const writeStream = gfs.createWriteStream({
        filename: file.filename,
    });
    fs.createReadStream(file.path).pipe(writeStream);
    writeStream.on('close', file => {
        const {_id} = file;
        return Account.findByIdAndUpdate(uid, {'employer.logo': _id}).then(() => res.redirect('/employer')).catch(e => console.log(e));
    });
},

How can I optimize the image before the upload? Preferably if there is something gulp-like but for the server?


Solution

  • I ended up using this https://github.com/imagemin/imagemin. It's pretty straight forward. Here's my code:

    async uploadImage(file, uid, res) {
        const imagemin = require('imagemin');
        const imageminJpegtran = require('imagemin-jpegtran');
        const imageminPngquant = require('imagemin-pngquant');
        console.log(1);
        // const newFilePath = `${file.path}optimized`;
        const newFile = await imagemin([file.path], newPath, {
            plugins: [
                imageminJpegtran(),
                imageminPngquant({quality: '65-80'})
            ]
        });
        // newFile.path = newFilePath;
        console.log(2);
        console.log(file);
        console.log(newFile);
        var fs = require('fs');
        await mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
        var conn = mongoose.connection;
        Grid.mongo = mongoose.mongo;
        const gfs = Grid(conn.db);
        const writeStream = gfs.createWriteStream({
            filename: newFile.filename,
        });
        fs.createReadStream(newFile.path).pipe(writeStream);
        writeStream.on('close', file => {
            const {_id} = file;
            return Account.findByIdAndUpdate(uid, {'employer.logo': _id}).then(() => res.redirect('/employer')).catch(e => console.log(e));
        });
    },