Max P
Max P

Reputation: 1459

Checking file after creating. FS + timeout?

After ajax request, I send options for Image Magick (child process) and create file. If I send response to client immediately - I have error - img non exist. My solution, set Timeout and send response (hardcode). I can set timeout and check file with fs module, but it is right way? Or may be I can emit new event after file exist, but can you type sample for me? Or this task have another solution?

fs.stat(currentImage, function(err, background) {

        if (background && background.isFile) {

            async.series([
                function(callback) {
                    var magickOpts = memOptions;
                    var im = spawn('convert', magickOpts);
                    callback(null, 'done');
                }
            ],
            function(err, result) { 
                setTimeout(function() {
                    res.send({
                        status: '200',
                        src: '/images/mems/'+tempName+'.jpg',
                        tempName: tempName
                    }); 
                }, 500);
            });

        } else {
            res.send({
                status: '404',
                text: 'background image not found'
            });
        }

    });

Upvotes: 0

Views: 254

Answers (1)

robertklep
robertklep

Reputation: 203231

You should wait for the child process to exit (by listening for the close event) before you send the response to the client.

Also, async.series doesn't seem to be really used in this case, so I left it out:

fs.stat(currentImage, function (err, background) {

  if (background && background.isFile) {
    var magickOpts = memOptions;
    var im = spawn('convert', magickOpts);
    im.on('close', function() { 
      res.send({
        status: '200',
        src: '/images/mems/' + tempName + '.jpg',
        tempName: tempName
      });
    });
  } else {
    res.send({
      status: '404',
      text: 'background image not found'
    });
  }

});

By the way, there's also the im package which wraps ImageMagick for use in Node.

Upvotes: 1

Related Questions