简体   繁体   English

在JavaScript中将字符串前置到文件?

[英]Prepend string to a file in javascript?

My js lives inside a FF addon so has access to prilivaged api . 我的js驻留在FF addon因此可以访问prilivaged api Currently I'm able to append a string to a file or truncate a file and write the string . 目前,我可以将字符串追加到文件或截断文件并写入string

But is there an easy way to prepend a string to a file? 但是,是否有一种简单的方法可以在文件前添加string So my string is placed at the beginning of file, then existing content follows. 因此,我的string放在文件的开头,然后是现有内容。

new file 新文件

FileUtils.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE)

append to file 附加到文件

FileUtils.openFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_APPEND)

main.js contents .. main.js内容..

Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");

var filename = 'test.txt',
    ostream,
    string = 'test content',
    file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
    file.initWithPath('/home/user/');
    file.append(fileName);

try {

    if (file.exists() === false) {
        file.create(Ci.nsIFile.NORMAL_FILE_TYPE, 420);
    }

    ostream = FileUtils.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
    var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
    converter.charset = "UTF-8";
    var istream = converter.convertToInputStream(combinedString);

    NetUtil.asyncCopy(istream, ostream, function (status) {

        if (!components.isSuccessCode(status)) {
            console.log('success: ' + file.path);
        } else {
            console.log('error: ' + file.path);
        }
    });
} catch (e) {
    return false;
}

Used OS.File in the end, reading file contents, prepending string to data then writing combined data back to file .. 最后使用OS.File ,读取文件内容,在数据前添加字符串,然后将组合数据写回到file ..

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM