node.js在覆盖时无法提供图像

我有一个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; } 

我build议将新版本的图像写入临时文件:

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

并在完全下载文件时对其进行重命名 :

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

我们使用'finish'事件 ,当所有的数据都被写入底层系统时,会触发'finish'事件 。 文件系统。

可能是更好的

  • 下载时服务旧版本的文件;
  • 将新文件下载到临时文件(比如说_fileName );
  • 下载后重命名文件,重写原文件;