簡體   English   中英

node.js在覆蓋時無法提供圖像

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

我有一個node.js應用程序,該應用程序定期輪詢圖像並將其存儲到文件系統中。

問題是,當node.js覆蓋圖像時,那時訪問該網站的任何人到處都會看到空白圖像(因為此時圖像已被覆蓋)。

每當需要輪詢圖像時,這種情況只會持續幾秒鍾,但這很煩人。 無論如何,在我們覆蓋圖像時是否仍然可以提供圖像?

保存/覆蓋圖像的代碼:

// 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.");
        }
    });
}

投放圖片的代碼:

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;
        } 

我建議將圖像的新版本寫入一個臨時文件:

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

並在文件完全下載后重命名

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

我們使用'finish'事件 ,當所有數據都已寫入底層系統時即觸發。 文件系統。

也許更好

  • 下載時提供舊版本的文件;
  • 將新文件下載到臨時文件(例如_fileName );
  • 下載后重命名文件,從而重寫原始文件;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM