Javascript write file without overwrite

前提是你 提交于 2019-12-11 08:44:27

问题


I am using XPCOM to read/write file(s) on my hard drive (since Java is no longer supported on FF16,17,18,+ I have to use this). I use it in my FireFox extension(s) (I use iMacros). On this document click I found this example.

var string = '\u5909\u63db\u30c6\u30b9\u30c8';
file.initWithPath('C:\\temp\\temp.txt');
file.create(file.NORMAL_FILE_TYPE, 0666);
var charset = 'EUC-JP';
var fileStream = Components
.classes['@mozilla.org/network/file-output-stream;1']
.createInstance(Components.interfaces.nsIFileOutputStream);
fileStream.init(file, 2, 0x200, false);
var converterStream = Components
.classes['@mozilla.org/intl/converter-output-stream;1']
.createInstance(Components.interfaces.nsIConverterOutputStream);
converterStream.init(fileStream, charset, string.length,
Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
converterStream.writeString(string);
converterStream.close();
fileStream.close();

So this code does the following. If file doesn't exist it creates it and saves the data in it. However if file does exists it will return error. If I comment that part of the code (and file exists) it will just overwrite the old data and put the new.

I need this code to create file, if it exists just move on without an error and save the data in the new line without overwriting.

Like this.

before:

data11, data12, data13
data21, data22, data23

after:

data11, data12, data13
data21, data22, data23
data31, data32, data33
data41, data42, data43

回答1:


Try passing 18 as the second parameter when you init the output stream (instead of 2).

fileStream.init(file, 18, 0x200, false);

That adds the PR_APPEND flag to the io mode parameter (it's 0x10; the 2 is for PR_WRONLY).



来源:https://stackoverflow.com/questions/14490710/javascript-write-file-without-overwrite

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