[英]Firefox Extension Write data to File
I have a hashTable like data set in my Firefox extension, and I am willing to save that in a simple text file. 我在Firefox扩展中有一个hashTable之类的数据集,我愿意将其保存在一个简单的文本文件中。 I have been going through a lot of sample codes but none of those are working for me.
我已经遍历了很多示例代码,但是没有一个对我有用。 For example, 1 , 2 .
例如, 1 , 2 。 I am a beginner in developing extensions on Firefox, and it seems to me the syntax for writing to a file is a bit complicated.
我是在Firefox上开发扩展的初学者,在我看来,写入文件的语法有点复杂。 Can anyone give me a working example?
谁能给我一个可行的例子? BTW, I am using unix.
顺便说一句,我正在使用unix。 Because I saw example for writing to a file that they were using windows system calls.
因为我看到了使用Windows系统调用写入文件的示例。
Here's some example code to write a file called myfile.txt to your firefox profile directory: 以下是一些示例代码,可将名为myfile.txt的文件写入您的firefox配置文件目录:
var txt = "my file contents";
var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
file.append("myfile.txt");
var fs = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
fs.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
fs.write(txt, txt.length);
fs.close();
If you are using the Firefox Addon SDK (jetpack), you'll need to modify it a bit. 如果您使用的是Firefox插件SDK(jetpack),则需要对其进行一些修改。
var {Cc, Ci} = require("chrome");
var txt = "my file contents";
var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile);
file.append("myfile.txt");
var fs = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
fs.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
fs.write(txt, txt.length);
fs.close();
This is the easier and straight forward way: 这是更简单直接的方法:
Components.utils.import("resource://gre/modules/osfile.jsm");
// Saving the pointed filename into your Firefox profile
let whereToSave = OS.Path.join(OS.Constants.Path.profileDir, "YOUR-FILENAME.txt");
// Convert your "hash table" to a Typed Array[1]
let dataToSave = hashTableAsArrayBufferView;
// Check MDN[2] for writeAtomic() details
OS.File.writeAtomic(whereToSave, dataToSave).then(function(aResult) {
// Write operation finished
...
}, Components.utils.reportError);
[1] : https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView [1]: https : //developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView
[2] : https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread#OS.File.writeAtomic%28%29 [2]: https : //developer.mozilla.org/zh-CN/docs/JavaScript_OS.File/OS.File_for_the_main_thread#OS.File.writeAtomic%28%29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.