如何读取Firefox版本45+的附加组件中的本地文件

时间:2016-09-05 20:15:36

标签: javascript firefox-addon xul firefox-addon-overlay

我花了4个小时试图找到一个解决方案,将文件加载到我的Firefox附加组件中。但是,没有成功((。(

我的代码:

const {TextDecoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
var decoder = new TextDecoder();
var promise = OS.File.read("C:\\test.txt");
promise = promise.then(function onSuccess(array) {
    alert(decoder.decode(array));
});

无法强制执行上面的代码(((。我做错了什么?

1 个答案:

答案 0 :(得分:0)

你所拥有的代码基本上是按照书面形式工作的。但是,这假定alert()已定义,并且在您尝试读取文件时没有错误。但是,通常不会定义alert(),除非您已在代码中的其他位置定义它。如果你查看Browser Console Ctrl - Shift - J <,那么完全问题可能会被确定OSX上的/ kbd>,或 Cmd - Shift - J 。不幸的是,您没有在问题中包含该信息。

参考资料:

下面是一个完整的Firefox附加SDK扩展,它可以在B:\testFile.txt两次读取并输出到控制台的文件。下面包含的示例文本文件的控制台输出是:

read-text-file:readTextFile: This is a text file line 1
Line 2
read-text-file:readUtf8File: This is a text file line 1
Line 2

index.js

var {Cu} = require("chrome");
//Open the Browser Console (Used in testing/developmenti to monitor errors/console)
var utils = require('sdk/window/utils');
activeWin = utils.getMostRecentBrowserWindow();
activeWin.document.getElementById('menu_browserConsole').doCommand();
var buttons     = require('sdk/ui/button/action');
var button = buttons.ActionButton({
    id: "doAction",
    label: "Do Action",
    icon: "./myIcon.png",
    onClick: doAction
});
//Above this line is specific to the Firefox Add-on SDK
//Below this line will also work for Overlay/XUL and bootstrap/restartless add-ons
//const Cu = Components.utils; //Uncomment this line for Overlay/XUL and bootstrap add-ons
const { TextDecoder, OS } = Cu.import("resource://gre/modules/osfile.jsm", {});
function doAction(){
    var fileName = 'B:\\textFile.txt'
    //Read the file and log the contents to the console.
    readTextFile(fileName).then(console.log.bind(null,'readTextFile:'))
                          .catch(Cu.reportError);
    //Do it again, using the somewhat shorter syntax for a utf-8 encoded file
    readUtf8File(fileName).then(console.log.bind(null,'readUtf8File:'))
                          .catch(Cu.reportError);
}
function readTextFile(fileName){
    var decoder = new TextDecoder();
    return OS.File.read(fileName).then(array => decoder.decode(array));
}
function readUtf8File(fileName){
    //Using the somewhat shorter syntax for a utf-8 encoded file
    return OS.File.read(fileName, { encoding: "utf-8" }).then(text => text);
}

的package.json

{
    "title": "Read a text file",
    "name": "read-text-file",
    "version": "0.0.1",
    "description": "Reads a text file in two different ways.",
    "main": "index.js",
    "author": "Makyen",
    "engines": {
        "firefox": ">=38.0a1",
        "fennec": ">=38.0a1"
    },
    "license": "MIT",
    "keywords": [
        "jetpack"
    ]
}

TextFile.txt的

This is a text file line 1
Line 2