如何使用Javascript覆盖CSV?

时间:2015-02-04 05:12:06

标签: javascript csv

经过一番搜索,我找到了一个方便的功能,可以与iMacros一起使用,将字符串保存为CSV文件。问题是我无法弄清楚如何覆盖文件。以下代码仅将数据附加到文件中。感谢。

function WriteFile(path,string) {
    //Import FileUtils.jsm
    Components.utils.import("resource://gre/modules/FileUtils.jsm");

    //Declare file
    var file = new FileUtils.File(path);

    //Declare file path
    file.initWithPath(path);

    //If it exists move on if not create it
    if (!file.exists()) {
        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, 18, 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);

    //Write file to location
    converterStream.writeString(string); //+"\r\n"
    converterStream.close();
    fileStream.close();
}

1 个答案:

答案 0 :(得分:0)

Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");

// file is nsIFile, data is a string

// You can also optionally pass a flags parameter here. It defaults to
// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
var ostream = FileUtils.openSafeFileOutputStream(file);

var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);

// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
  if (!Components.isSuccessCode(status)) {
    // Handle error!
    return;
  }

  // Data has been written to the file.
});

阅读上面的示例,从此链接中获取。https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O。您应该为其指定pass标志参数。