![](/img/trans.png)
[英]Node.js: reading a picture which is being overwritten, references the initial image only
[英]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.