2016-09-05 5 views
2

4 시간 동안 Firefox Add-on에 파일을로드하는 솔루션을 찾으려고했습니다. 그러나, 아니 성공 (과 ((Firefox의 부가 기능에서 로컬 파일을 읽는 방법 45 +

내가 가진 코드 :..이

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)); 
}); 

그것은 (실행하려면 위의 코드를 강제하는 것은 불가능하다 ((내가 뭘 잘못하고

+0

try/catch에서'OS.File.read()'를 래핑하고 OS.File.Error가 던져 졌는지 확인해 보셨습니까? https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File.Error –

+0

[종류의 Firefox 확장 기능] (https://developer.mozilla.org/en- (WebExtensions) (https://developer.mozilla.org/en-US/Add-ons/WebExtensions), [[태그 : fiirefox- addon-sdk]] [애드온 SDK] (https://developer.mozilla.org/en-US/Add-ons/SDK), [[태그 : firefox-addon-restartless]] [부트 스트랩 됨] (https : //developer.mozilla.org/en/US/Add-ons/Bootstrapped_extensions) 또는 [[tag : fiirefox-addon-overlay]] [오버레이/XUL/레거시] (https://developer.mozilla.org/en) -US/Add-ons/Overlay_Extensions))? 귀하의 질문에 해당하는 태그를 [편집]하십시오. – Makyen

+0

[브라우저 콘솔] (https://developer.mozilla.org/en/US/docs/Tools/Browser_Console) (Ctrl-Shift-J 또는 OSX의 Cmd-Shift-J)에 * 정확하게 * 표시되었습니다. 이 코드를 실행할 때? – Makyen

답변

0

코드? 그러나 기본적으로는 alert()이 정의되어 있고 파일을 읽으려고 할 때 아무런 오류가 없다고 가정합니다. 그러나 alert()은 코드에서 다른 곳에 정의하지 않는 한 정상적으로 정의되지 않습니다. 무엇 정확히 문제가 확정 될 수 있습니다. 에드 당신은 Browser Console에보고하는 경우 (Ctrl 키 - 시프트 - J, 또는 Cmd를 - 시프트 - OSX에 J을). 불행히도, 당신은 질문에 그 정보를 포함하지 않았습니다.

참고 정보 : 아래

는 완전한 파이어 폭스 애드온에 두 번 콘솔에 읽고 출력 SDK 확장에있는 파일.

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 
+0

동기화 모드에서 읽을 수 있습니까? – Greccy

+0

Greccy, 주저하지 않습니다. 메인 UI 스레드에서 그런 방식으로 사용하려고하지 않았습니다. . 작업자 스레드에서 사용하는 경우 그 방법으로 파일을 만드십시오. [MDN이 비동기 적이어야하는 이유를 설명하는 텍스트] (https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile)입니다. jsm # FAQ) : "모든 개발자가 기억해야 할 한 가지는 File I/O 작업의 지속 시간이 제한되어 있지 않다는 것입니다. [계속] – Makyen

+0

@Greccy, [계속] 커널의 현재로드에 따라 현재 디스크 활동, 버스의 현재 부하, 디스크의 현재 회전 속도, 배터리 p의 양 ower 등의 작업에는 임의의 시간이 걸릴 수 있습니다. 우리는 파일을 닫거나 마지막으로 수정 한 시간을 확인하는 것처럼 사소한 것처럼 보이는 작업을 실행하는 데 몇 초가 걸렸습니다. 메인 스레드에서 작업이 호출되면 이는 전체 사용자 경험이 몇 초 동안 멈추었 음을 의미합니다. " – Makyen