知道永远不会调用onSuccess
的原因吗?
filesystem ..
rob@work:~$ cat test.txt
hello
hello2
rob@work:~$ 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 :(得分: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;
}
});