2017-02-17 67 views
1

我真的很努力寻找文档如何读取文本文件到使用OS X自动化与JavaScript的数组。阅读文本文件到一个数组与OS X Javascript

这是我到目前为止有:

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

var myFile = "/Users/Me/Dropbox/textfile.txt"; 
var openedFile = app.openForAccess(myfile, { writePermission: true }); 

var myText = openedFile.?? 

app.closeAccess(URLFile); 

我复制这个最从苹果官方文档。我发现很难在网上找到任何文档。例如,什么是openForAccess的参数?似乎没有任何字典中的任何内容来描述该方法。

我在与JXA浪费时间吗?

+0

对于应用程序的自动化,AppleScript的是唯一的支持正确选项,并有文档和社区支持。对于其他任务,如果您可以使用Python,Ruby,Swift或其他主动维护并具有健康用户社区的语言,那么请执行此操作。从发货的第一天起,JXA就已经得到了有效的解决,并且没有得到任何支持,所以毫不意外地没有建立任何市场份额,最终在去年解雇了自动化产品经理和麦克自动化团队,结果可能不是一个好的长期投资。 – foo

+0

JXA是一个非常有用的工具。 – houthakker

回答

0

Apple的an entire page致力于在他们的Mac自动化脚本指南中读取和写入文件。这包括一个执行您正在查找的动作的功能。我重新写你的下面的示例使用readAndSplitFile功能从苹果指南:

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

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

    // Read the file using a specific delimiter and return the results 
    return app.read(Path(fileString), { usingDelimiter: delimiter }) 
} 

var fileContentsArray = readAndSplitFile('/Users/Me/Dropbox/textfile.txt', '\n') 

运行上面的代码后,fileContentsArray将举行一个字符串数组,每个字符串方含该文件的单行。 (你也可以使用\t作为分隔符在每个选项卡断,或您选择的任何其它字符。)

1

一些通用的功能和说明性测试:

(function() { 
    'use strict'; 

    // GENERIC FUNCTIONS ------------------------------------------------------ 

    // doesFileExist :: String -> Bool 
    function doesFileExist(strPath) { 
     var error = $(); 
     return $.NSFileManager.defaultManager 
      .attributesOfItemAtPathError($(strPath) 
       .stringByStandardizingPath, error), error.code === undefined; 
    }; 

    // lines :: String -> [String] 
    function lines(s) { 
     return s.split(/[\r\n]/); 
    }; 

    // readFile :: FilePath -> maybe String 
    function readFile(strPath) { 
     var error = $(), 
      str = ObjC.unwrap(
       $.NSString.stringWithContentsOfFileEncodingError($(strPath) 
        .stringByStandardizingPath, $.NSUTF8StringEncoding, error) 
      ), 
      blnValid = typeof error.code !== 'string'; 
     return { 
      nothing: !blnValid, 
      just: blnValid ? str : undefined, 
      error: blnValid ? '' : error.code 
     }; 
    }; 

    // show :: a -> String 
    function show(x) { 
     return JSON.stringify(x, null, 2); 
    }; 

    // TEST ------------------------------------------------------------------- 
    var strPath = '~/DeskTop/tree.txt'; 

    return doesFileExist(strPath) ? function() { 
     var dctMaybe = readFile(strPath); 
     return dctMaybe.nothing ? dctMaybe.error : show(lines(dctMaybe.just)); 
    }() : 'File not found:\n\t' + strPath; 
})();