How to check whether a folder exists on JXA?

I would like to use Javascript for Automation to check whether a given folder exists. Does anyone know how to do that?

Posted on Dec 23, 2018 10:40 AM

Reply
Question marked as Top-ranking reply

Posted on Dec 23, 2018 12:46 PM

The last example was not exactly correct:


ObjC.import('Foundation')

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

var path = Path('/Users/yourname/Desktop/Test_Folder').toString();
app.displayAlert(path);

isDir=Ref();
$.NSFileManager.alloc.init.fileExistsAtPathIsDirectory(path, isDir);
app.displayAlert(isDir[0]);

3 replies
Question marked as Top-ranking reply

Dec 23, 2018 12:46 PM in response to VikingOSX

The last example was not exactly correct:


ObjC.import('Foundation')

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

var path = Path('/Users/yourname/Desktop/Test_Folder').toString();
app.displayAlert(path);

isDir=Ref();
$.NSFileManager.alloc.init.fileExistsAtPathIsDirectory(path, isDir);
app.displayAlert(isDir[0]);

Dec 23, 2018 12:30 PM in response to nyaastudioapps

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


var path = Path('/Users/yourname/Desktop/Test_Folder');
var finderApp = Application("Finder");
var status = finderApp.exists(path);
app.displayAlert(status);


This is the simplest approach. It can also be done as:


ObjC.import('Foundation')

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

var path = Path('/Users/yourname/Desktop/Test_Folder');

isDir=Ref()
$.NSFileManager.alloc.init.fileExistsAtPathIsDirectory(path, isDir);
app.displayAlert(isDir[0]);


In the latter case, it will be true if the object at the end of the path is a directory, and it exists, otherwise false is returned.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to check whether a folder exists on JXA?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.