Documentation Archive

Developer

Mac Automation Scripting Guide

Prompting for a File Name

Use the Standard Additions scripting addition’s choose file name command to display a save dialog that lets the user enter a file name and choose an output folder, such as the one produced by Listing 27-1 and Listing 27-2, shown in Figure 27-1.

Figure 27-1Prompting for a file name image: ../Art/choosefilename_2x.png

APPLESCRIPT

Open in Script Editor

Listing 27-1AppleScript: Prompting for a file name
  1. set theNewFilePath to choose file name with prompt "Save the document as:"
  2. --> Result: file "Macintosh HD:Users:yourUserName:Desktop:ImportantDocument"

JAVASCRIPT

Open in Script Editor

Listing 27-2JavaScript: Prompting for a file name
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var newFilePath = app.chooseFileName({
  4. withPrompt: "Save the document as:"
  5. })
  6. newFilePath
  7. // Result: Path("/Users/yourUserName/Desktop/ImportantDocument")

If the specified file name already exists in the output folder when the user clicks the Save button, the user is prompted to replace it, as shown in Figure 27-2.

Figure 27-2Prompting to replace an existing file image: ../Art/choosefilename_replacing_2x.png

The result of the choose file name command is a path to a potential file. This file may or may not already exist. However, if it does exist, you can assume the user wants to replace it. Your script can now safely write or save a file to the path.

Listing 27-3 and Listing 27-4 ask the user to type some text as a note and choose an file name and output folder, and then save the note in the specified file.

APPLESCRIPT

Open in Script Editor

Listing 27-3AppleScript: Saving content in a specified file
  1. set theResponse to display dialog "Enter a note:" default answer ""
  2. set theNote to text returned of theResponse
  3. set theNewFilePath to choose file name with prompt "Save the document as:"
  4. writeTextToFile(theNote, theNewFilePath, true)
  5. on writeTextToFile(theText, theFile, overwriteExistingContent)
  6. try
  7. -- Convert file to a string
  8. set theFile to theFile as string
  9. -- Open file for writing
  10. set theOpenedFile to open for access file theFile with write permission
  11. -- Clear file if content should be overwritten
  12. if overwriteExistingContent is true then set eof of theOpenedFile to 0
  13. -- Write new content to file
  14. write theText to theOpenedFile starting at eof
  15. -- Close file
  16. close access theOpenedFile
  17. -- Return a boolean indicating that writing was successful
  18. return true
  19. -- Handle a write error
  20. on error
  21. -- Close file
  22. try
  23. close access file theFile
  24. end try
  25. -- Return a boolean indicating that writing failed
  26. return false
  27. end try
  28. end writeTextToFile

JAVASCRIPT

Open in Script Editor

Listing 27-4JavaScript: Saving content in a specified file
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var response = app.displayDialog("Enter a note:", {
  4. defaultAnswer: ""
  5. })
  6. var note = response.textReturned
  7. var newFilePath = app.chooseFileName({
  8. withPrompt: "Save document as:"
  9. })
  10. writeTextToFile(note, newFilePath, true)
  11. function writeTextToFile(text, file, overwriteExistingContent) {
  12. try {
  13. // Convert file to a string
  14. var fileString = file.toString()
  15. // Open file for writing
  16. var openedFile = app.openForAccess(Path(fileString), { writePermission: true })
  17. // Clear file if content should be overwritten
  18. if (overwriteExistingContent) {
  19. app.setEof(openedFile, { to: 0 })
  20. }
  21. // Write new content to file
  22. app.write(text, { to: openedFile, startingAt: app.getEof(openedFile) })
  23. // Close file
  24. app.closeAccess(openedFile)
  25. // Return a boolean indicating that writing was successful
  26. return true
  27. }
  28. catch (error) {
  29. try {
  30. // Close file
  31. app.closeAccess(file)
  32. }
  33. catch(error) {
  34. // Report error is closing failed
  35. console.log(`Couldn't close file: ${error}`)
  36. }
  37. // Return a boolean indicating that writing was successful
  38. return false
  39. }
  40. }