如何使用JXA将LZ压缩字符串写入文本文件?

时间:2019-06-12 01:43:06

标签: javascript objective-c cocoa lzo javascript-automation

我试图在Apple脚本编辑器中编写一个JXA脚本,该脚本使用LZ算法压缩字符串并将其写入文本(JSON)文件:

var story = "Once upon a time in Silicon Valley..."
var storyC = LZString.compress(story)
var data_to_write = "{\x22test\x22\x20:\x20\x22"+storyC+"\x22}"
app.displayAlert(data_to_write)
var desktopString = app.pathTo("desktop").toString()
var file = `${desktopString}/test.json`
writeTextToFile(data_to_write, file, true)

一切正常,除了LZ压缩的字符串只是转换为一组“?”到达输出文件 test.json 的时间。

它应该像这样:

{"test" : "㲃냆੠Њޱᐈ攀렒삶퓲ٔ쀛䳂䨀푖㢈Ӱນꀀ"}

相反,它看起来像:

{"test" : "????????????????????"}

我感觉转换是在 writeTextToFile()函数使用的 app.write 命令中进行的(我从{{3} }):

var app = Application.currentApplication()
app.includeStandardAdditions = true

function writeTextToFile(text, file, overwriteExistingContent) {
    try {

        // Convert the file to a string
        var fileString = file.toString()

        // Open the file for writing
        var openedFile = app.openForAccess(Path(fileString), { writePermission: true })

        // Clear the file if content should be overwritten
        if (overwriteExistingContent) {
            app.setEof(openedFile, { to: 0 })
        }

        // Write the new content to the file
        app.write(text, { to: openedFile, startingAt: app.getEof(openedFile) })

        // Close the file
        app.closeAccess(openedFile)

        // Return a boolean indicating that writing was successful
        return true
    }
    catch(error) {

        try {
            // Close the file
            app.closeAccess(file)
        }
        catch(error) {
            // Report the error is closing failed
            console.log(`Couldn't close file: ${error}`)
        }

        // Return a boolean indicating that writing was successful
        return false
    }
}

是否有 app.write 的替代命令来维护LZ压缩字符串/更好的方式来完成我想做的事情?

此外,我正在使用 readFile()函数(也来自Apple's Mac Automation Scripting Guide)将LZ字符串重新加载到脚本中:

function readFile(file) {
    // Convert the file to a string
    var fileString = file.toString()

    // Read the file and return its contents
    return app.read(Path(fileString))
}

但不返回:

{"test" : "㲃냆੠Њޱᐈ攀렒삶퓲ٔ쀛䳂䨀푖㢈Ӱນꀀ"}

正在返回:

"{\"test\" : \"㲃냆੠Њޱᐈ攀렒삶퓲ٔ쀛䳂䨀푖㢈Ӱນꀀ\"}"

有人也知道解决办法吗?

我知道可以Scripting Guide,所以解决方案就在其中吗?

我刚开始使用JavaScript,所以我承认尝试掌握Objective-C或Swift远远超出了我的范围。

我期待您可能提供给我的任何解决方案和/或指示。预先感谢!

1 个答案:

答案 0 :(得分:0)

经过进一步的Googl'ing操作后,我遇到了以下两个帖子:

因此,我相应地更改了脚本。

writeTextToFile()现在看起来像:

function writeTextToFile(text, file) {
  // source: https://stackoverflow.com/a/44293869/11616368
  var nsStr       = $.NSString.alloc.initWithUTF8String(text)
  var nsPath      = $(file).stringByStandardizingPath
  var successBool  = nsStr.writeToFileAtomicallyEncodingError(nsPath, false, $.NSUTF8StringEncoding, null)
  if (!successBool) {
    throw new Error("function writeFile ERROR:\nWrite to File FAILED for:\n" + file)
  }
  return successBool  
};

readFile()如下:

ObjC.import('Foundation')
const readFile = function (path, encoding) {
  // source: https://github.com/JXA-Cookbook/JXA-Cookbook/issues/25#issuecomment-271204038
    pathString = path.toString()
    !encoding && (encoding = $.NSUTF8StringEncoding)
    const fm = $.NSFileManager.defaultManager
    const data = fm.contentsAtPath(pathString)
    const str = $.NSString.alloc.initWithDataEncoding(data, encoding)
    return ObjC.unwrap(str)
};

都使用Objective-C来克服 app.write app.read 无法处理UTF-8的问题。