Script Editor에서
자바스크립트 이용하여 파일 저장, 불러오기
자바스크립트에서는 인터넷 보안 상 파일을 저장하는 기능을 제공하지 않기 때문에, Script Editor 에서도 관련 기능을 사용할 수 없습니다. 파일을 다루기 위해서는 애플 스크립트(AppleScript)의 기능을 빌려 사용해야하는데, 그 기능들이 바로 StandardAdditions에 저장되어져 있고, 이것을 이용하면 관련기능을 구현할 수 있습니다. 이번 포스트에서는 파일의 저장과 불러오는 방법에 대해서 알아 보겠습니다.
[1] 파일 저장하기
[1.1] writeTextToFile 함수 작성
파일을 저장하는 함수 writeTextToFile를 코딩해 보겠습니다.
var app = Application.currentApplication();
app.includeStandardAdditions = true;
function writeTextToFile(text, file, overwriteExistingContent) {
try {
// Convert the file to a string
let fileString = file.toString();
// Open the file for writing
let 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
}
}
[1.2] 사용방법
writeTextToFile은 3가지 매개변수를 받습니다. 첫 번째 매개변수는 파일에 저장할 내용에 해당하고, 두 번째 매개변수는 파일를 생성할 경로에 해당합니다. 세 번째 매개변수는 true 또는 false 값을 받는데, true인 경우에는 파일을 덮어 써버리고, false인 경우에는 (같은 이름의 파일이 존재할 경우) 기존 내용의 뒷 부분에 이어서 내용을 저장합니다.
example.txt 파일에 “hello world”라는 내용을 저장하려고 한다면, 다음과 같이 작성할 수 있습니다. Script Editor를 실행을 해보면 downloads 폴더 안에 exmple.txt가 생성되었음을 확인할 수 있습니다. 파일을 열어보면 “hello world”가 저장되어져 있습니다. Script Editor를 한번 더 실행한 뒤 파일을 열어보면, 그대로 “hello world”라는 글자가 있습니다. 왜냐하면 3번째 인자에 true로 설정했기 때문에 덮어쓰기가 되었기 때문입니다. 참고로 아래 file 변수 경로는 본인의 상황에 맞게 실제 경로를 넣어주면 됩니다.
var file = "/Users/유저이름/Downloads/example.txt";
writeTextToFile("hello world", file, true);
만약 기존의 example.txt 파일 뒤에 이어서 내용을 저장하고 싶다면 다음과 같이 작성할 수 있습니다. Script Editor를 여러번 실행한 뒤 파일을 열어보면, “hello worlhello worlhello worlhello worlhello worlhello world”와 같은 형태로 이어져 저장되었음을 확인할 수 있습니다.
var file = "/Users/유저이름/Downloads/example.txt";
writeTextToFile("hello world", file, false);
[2] 파일 로딩
[2.1] readFile 함수 작성
var app = Application.currentApplication();
app.includeStandardAdditions = true;
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))
}
[2.2] readFile 사용 방법
readFile 함수는 1개의 매개 변수를 받습니다. 이 매개 변수에 파일의 경로를 넣어주게 되면, 파일의 내용을 불러와서 결과값으로 리턴해줍니다. 위 코드에서 그 결과값을 “result” 변수에 저장하였고, 결과값을 팝업창으로 표시하였습니다. 만약에 섹션 1부터 따라서 코딩을 해주신 분들의 경우, Script Editor를 실행하면 팝업창에 “hello worlhello worlhello worlhello worlhello worlhello world”가 표시됨을 확인할 수 있을 것입니다.
var file = "/Users/유저이름/Downloads/example.txt";
var result = readFile(file);
app.displayDialog(result);
3번째 줄에 있는 app.displayDialog의 작동 방법이 궁금하신 분은 포스트(AppleScript를 JavaScript로 구현하기)를 보시기 바랍니다.
[2.3] readAndSplitFile 함수 작성
파일에 저장된 내용들을 특정 패턴으로 나눠서, 배열로 저장하는 방법이 있습니다. 특히 데이터를 불러오는 경우에 이러한 방법이 유용할 수 있습니다. 데이터 파일은 보통 탭이나 엔저로 값들이 나눠져 있습니다. delimiter에 탭(\t)이나 엔터(\n)을 넣어주면 데이터 값들을 배열로 나눠서 가져오게 됩니다.
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 })
}
[2.4] readAndSplitFile 사용 방법
readAndSplitFile 함수는 2개의 매개 변수를 받습니다. 첫 번째 file 매개 변수는 파일의 경로를 넣어주면 되고, 두 번째 delimiter에는 데이터 값들이 구분되어지는 delimiter를 넣어주면 됩니다. 예를 들어 data.txt 파일을 생성하고, “hello world”를 치고 엔터를 친 후 “Javascript”라고 입력 후 저장합니다. 그 이후 아래 코드를 실행해주면, “Messages” 탭을 보시면 “/* hello world,JavaScript */”가 출력됨을 확인할 수 있습니다.
“Messages” 탭을 여는 방법은 메뉴 View > Show Log를 클릭하시고, 창 아래에 있는 Messages 탭을 클릭하시면 됩니다.
var file = "/Users/유저이름/Downloads/data.txt";
var result = readAndSplitFile(file, "\n");
console.log(result);
