使用OS.file在javascript中为文件添加前缀
知道为什么从未调用成功的使用OS.file在javascript中为文件添加前缀,javascript,Javascript,知道为什么从未调用成功的onSuccess吗 文件系统 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/os
onSuccess
吗
文件系统
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中的唯一输出
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.
您确实意识到您只是在声明您的
onSuccess
函数,而从未使用过它,即它没有被用作read的then调用的第一个参数
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;
}
});