2014-12-20 32 views
0

任何想法为什么onSuccess永远不会被调用?在JavaScript中使用OS预先考虑文件。文件

文件系统..

[email protected]:~$ cat test.txt 
hello 
hello2 
[email protected]:~$ pwd 
/home/rob 

插件代码..

var filePath = '/home/rob/test.txt', 
    combinedString = 'new file content'; 

const {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {}); 

OS.File.read(filePath).then(function(data) { // check if specified file exists 

    console.log(data) 
    function onSuccess(array) { // prepend to file 
    let text = new TextDecoder().decode(array); 
    let encodedArray = new TextEncoder().encode(combinedString + text); 
    console.log('exists: ' + combinedString + text); 
    var promise = OS.File.writeAtomic(filePath, encodedArray); 
    promise.then(
     function() { 
     console.log('success'); 
     }, 
     function(ex) { 
     console.log('fail'); 
     } 
    ); 
    } 
}, function(ex) { // file doesn't exist, create a new one 
    if (ex.becauseNoSuchFile) { 
    let encodedArray = new TextEncoder().encode(combinedString); 
    var promise = OS.File.writeAtomic(filePath, encodedArray); 
    console.log('new: ' + combinedString + text); 
    promise.then(
     function() { 
     console.log('success'); 
     }, 
     function(ex) { 
     console.log('fail'); 
     } 
    ); 
    } 
}); 

这是在控制台中的唯一输出..

console.log: savetexttofile: Uint8Array {"0":104,"1":101,"2":108,"3":108,"4":111,"5":10,"6":104,"7":101,"8":108,"9":108,"10":111,"11":50,"12":10} 
Total time: 5.596181 seconds 
Program terminated successfully. 
+0

你一定要明白,你只是声明你的'onSuccess'函数并且从不使用它,也就是说没有被用作你的阅读的第一个参数然后调用 –

回答

0
let promise = OS.File.read(filePath); 
promise = promise.then(function onSuccess(contents) { 
    let text = new TextDecoder().decode(contents); 

    combinedString = combinedString + '\n\n' + text; 

    if (System.getPlatform().indexOf('win') >= 0) 
     combinedString = combinedString.replace(/[\n]/g, '\r\n'); 

    let encodedArray = new TextEncoder().encode(combinedString); 

    var promise = OS.File.writeAtomic(filePath, encodedArray); 
    promise.then(
    function() { 
     console.log('success'); 
    }, 
    function(ex) { 
     console.log('error'); 
    } 
); 
    return true; 
}, 
function onError(reason) { 
    if (System.getPlatform().indexOf('win') >= 0) 
    combinedString = combinedString.replace(/[\n]/g, '\r\n'); 
    let encodedArray = new TextEncoder().encode(combinedString); 
    if (reason.becauseNoSuchFile()) { 
     var promise = OS.File.writeAtomic(filePath, encodedArray); 
     promise.then(
     function() { 
      console.log('success'); 
     }, 
     function(ex) { 
      console.log('error'); 
     } 
    ); 
    return false; 
    } 
});