无法使用xul写入文件

时间:2012-11-30 07:07:30

标签: javascript firefox-addon xul xulrunner

尝试使用XUL代码在Windows临时目录中编写文件:

function writeFile_launch_application(utility_name,utility_path)
{
var data ='tasklist  /nh /fi "imagename eq '+utility_name+'" | find /i "'+utility_name+'">nul && (echo alerady running) || ("'+utility_path+'")';
//alert(data);
var file = Cc["@mozilla.org/file/directory_service;1"].
       getService(Ci.nsIProperties).
       get("TmpD", Ci.nsIFile);
        file.append("launch_application.bat");
        file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);

        // Then, we need an output stream to our output file.
        var ostream = Cc["@mozilla.org/network/file-output-stream;1"].
                      createInstance(Ci.nsIFileOutputStream);
        ostream.init(file, -1, -1, 0);

        // Finally, we need an input stream to take data from.
        const TEST_DATA = data;
        let istream = Cc["@mozilla.org/io/string-input-stream;1"].
                      createInstance(Ci.nsIStringInputStream);
        istream.setData(TEST_DATA, TEST_DATA.length);

        NetUtil.asyncCopy(istream, ostream, function(aResult) {
          if (!Components.isSuccessCode(aResult)) {
            // an error occurred!
          }
        })
}

但是得到错误:

Timestamp: 11/29/2012 11:03:09 PM
Error: ReferenceError: Cc is not defined
Source File: chrome://myaddon/content/overlay.js
Line: 199

我还尝试在代码顶部添加以下行,但它没有解决上述错误:

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

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

2 个答案:

答案 0 :(得分:1)

Cc和Ci分别是Components.classes和Components.interfaces的别名。

取决于他们可能(或可能不)已经定义的上下文。

无论如何

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cr = Components.results;

(您不应将问题标记为firefox-addon-sdk

答案 1 :(得分:0)

当我开发插件时,我总是尝试用Components.utilsComponents.intefaces替换CuCi。为此,我文件中的第一行是:

const { Cc, Ci, Cu } = require('chrome');

CcComponent.classes。比你现在可以使用

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