0

我的某些打印機出現問題,我的Chrome應用程序使用文件夾中的內容創建文件(.xml),然後打印機將其打印出來,但問題在於chrome首先創建空文件,然後寫入在它裏面的內容..chrome.filesystem創建文件並將其重命名

像這個問題的答案之一:"Premature end of file" error when Java read and writes XML data files

寫您的文件thename.xml.part,然後做一次/關閉到 重命名到thename.xml,這使得寫入更接近原子 - 讀者無法讀取它,直到它確實完成,只要它是 僅查找「.xml」文件。

我該如何在Chrome應用程序中做到這一點?

這是我到目前爲止的代碼:

chrome.fileSystem.getWritableEntry(printer_location, function(entry) { 
     var uniqid = (Math.floor((Math.random() * 10) + 1)+Date.now()).toString(); 
     entry.getFile(uniqid+'.xml', {create:true}, function(entry) { 
      entry.createWriter(function(writer) { 
       writer.write(new Blob([xmlPrintText], {type: 'text/plain'})); 
      }); 
     }); 
    }); 

此代碼創建文件,但我需要.part,然後創建完成時,它沒有。第二部分重新命名。

回答

0

實測溶液:

chrome.fileSystem.getWritableEntry(print_location, function(entry) { 
    var uniqid = (Math.floor((Math.random() * 10) + 1)+Date.now()).toString(); 
    var fileName = uniqid+'.xml'; 
    entry.getFile(fileName+'.part', {create:true}, function(entry) { 
     entry.createWriter(function(writer) { 
      writer.write(new Blob([xmlPrintText], {type: 'text/plain'})); 
      writer.onwriteend = function(e) { 
       rename(fileName+'.part', fileName); 
      }; 
     }); 
    }); 
}); 
function rename(oldName, newName) { 
    chrome.fileSystem.getWritableEntry(printer_location, function(entry) { 
     entry.getFile(oldName, {}, function(fileEntry) { 
      fileEntry.moveTo(entry, newName); 
     }); 
    }); 
}