How to overwrite a file in Chrome App?

微笑、不失礼 提交于 2019-12-10 13:43:42

问题


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 some existing file file1.txt and file2.txt.

But I found a problem: if the files are not empty, their content won't be fully overwritten, only the beginning part will be overwritten.

Do I need to remove the files first? Or do I miss something?


回答1:


It looks like write only overwrites the contents of the file at the specified position, so you are correct that if you want to completely replace the text of the file, you'd need to either remove the files first or truncate them.

This code worked for me, by truncating the file to the position of the writer after the write is finished.

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


来源:https://stackoverflow.com/questions/28710804/how-to-overwrite-a-file-in-chrome-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!