简体   繁体   中英

node.js unable to serve image when it is being overwritten

I have a node.js app that periodically poll images and store them onto filesystem.

The problem is, when node.js is overwriting the images, whoever that visits the website at that moment will see blank images everywhere (because the images is being overwritten at that moment).

This only happens for that few seconds whenever it is time to poll the images, but it is annoying. Is there anyway to be able to still serve the image while we are overwriting it?

Code to save/overwrite image:

// This method saves a remote path into a file name.
// It will first check if the path has something to download
function saveRemoteImage(path, fileName)
{
    isImagePathAvailable(path, function(isAvailable)
    {
        if(isAvailable)
        {
            console.log("image path %s is valid. download now...", path);   
            console.log("Downloading image file from %s -> %s", path, fileName);
            var ws = fs.createWriteStream(fileName);
            ws.on('error', function(err) { console.log("ERROR DOWNLOADIN IMAGE FILE: " + err); });
            request(path).pipe(ws);         
        }
        else
        {
            console.log("image path %s is invalid. do not download.");
        }
    });
}

Code to serve image:

fs.exists(filePath, function(exists) 
    {
        if (exists) 
        {
            // serve file
            var stat = fs.statSync(filePath);
            res.writeHead(200, {
                'Content-Type': 'image/png',
                'Content-Length': stat.size
            });

            var readStream = fs.createReadStream(filePath);
            readStream.pipe(res);
            return;
        } 

I'd suggest writing the new version of the image to a temporary file:

var ws = fs.createWriteStream(fileName + '.tmp');
var temp = request(path).pipe(ws);         

and renaming it when the file is entirely downloaded:

temp.on('finish', function() {
    fs.rename(fileName + '.tmp', fileName);
});

We use the 'finish' event , which is fired when all the data has been written to the underlying system, ie. the filesystem.

May be it is better to

  • serve the old version of file while downloading;
  • download new file to temporary file (say _fileName , for example);
  • rename file after downloading thus rewriting original file;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM