How to overwrite a file in a Chrome application?

I followed this example:

chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) { chrome.fileSystem.getWritableEntry(entry, function(entry) { entry.getFile('file1.txt', {create:true}, function(entry) { entry.createWriter(function(writer) { writer.write(new Blob(['Lorem'], {type: 'text/plain'})); }); }); entry.getFile('file2.txt', {create:true}, function(entry) { entry.createWriter(function(writer) { writer.write(new Blob(['Ipsum'], {type: 'text/plain'})); }); }); }); }); 

to overwrite the existing file1.txt and file2.txt .

But I found a problem: if the files are not empty, their contents will not be completely overwritten, only the initial part will be overwritten.

Do I need to delete files first? Or am I missing something?

+6
source share
1 answer

It seems that write only overwrites the contents of the file at the specified position , so you are right that if you want to completely replace the text of the file, you must either delete the files first or trim them.

This code worked for me, trimming the file to the recording position after the recording was completed.

 chrome.fileSystem.chooseEntry({type:'openDirectory'}, function(entry) { chrome.fileSystem.getWritableEntry(entry, function(entry) { entry.getFile('file1.txt', {create:true}, function(entry) { entry.createWriter(function(writer) { writer.onwriteend = function(e) { e.currentTarget.truncate(e.currentTarget.position); }; writer.write(new Blob(['Lorem'], {type: 'text/plain'})); }); }); entry.getFile('file2.txt', {create:true}, function(entry) { entry.createWriter(function(writer) { writer.onwriteend = function(e) { e.currentTarget.truncate(e.currentTarget.position); }; writer.write(new Blob(['Ipsum'], {type: 'text/plain'})); }); }); }); }); 
+3
source

Source: https://habr.com/ru/post/982971/


All Articles