Search code examples
javascriptmeteorgraphicsmagickcollectionfs

Same read- and write-stream in collectionFS using graphicsmagick


I need to manipulate an image using graphicsmagick.

My FSCollection looks like this:

Images = new FS.Collection("media", {
    stores: [
        new FS.Store.FileSystem("anything"),
        new FS.Store.FileSystem("something")
    ],
});

My problem is, that the writeStream should be the same like the readStream. And this doesn't work as this leads to an empty result:

var read  = file.createReadStream('anything'),
    write = file.createWriteStream('anything');

gm(read)
    .crop(100,100,10,10)
.stream()
.on('end',function(){ console.log('done'); })
.on('error',function(err){ console.warn(err); })
.pipe(write, function (error) {
    if (error) console.log(error);
    else console.log('ok');
});

Solution

  • Simultaneously reading from and writing to the same file is not possible since you would be overwriting content at the same time you were trying to read from it. Write to a different file and then rename it to the original.

    var read  = file.createReadStream('anything'),
        write = file.createWriteStream('anything-writeTo');
    
    gm(read)
        .crop(100,100,10,10)
    .stream()
    .on('error',function(err){ console.warn(err); })
    .pipe(write, function (error) {
        if (error) console.log(error);
        else console.log('ok');
    })
    .on('end',function(){
        file.rename("anything-writeTo", "anything", function (err) {
            if (err) console.error(err);
            else console.log('rename complete');
        });
    })