Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaScript to determine whether a directory exists?

Tags:

javascript

I have written the following code to write a file on my local file system:

writeToFile : function(msg) {
    var fso  = new ActiveXObject("Scripting.FileSystemObject");
    fh = fso.CreateTextFile("c:\\QHHH\\myXML.xml", true);
    fh.WriteLine(msg);
    fh.Close();
}

What I want now is to check if the directory(the one I have specified in code snippet above) even exists or not already? I want to throw an exception or simply show an alert to the user that "Please specify a directory you want to store your file into" and anything like this.
So my questions are:
1.Is it possible to check if the specified directory exists or not ?
2.Is it possible to create the directory on the fly and store the file in there automatically?

Please don't bother that accessing local file system is bad or anything else. I am creating this for my own personal use and I am well aware of this fact.
Please try to answer in native javascript, I am not using JQuery or any other framework.

Many Thanks

like image 365
EMM Avatar asked Dec 16 '22 11:12

EMM


2 Answers

This should work:

var sFolderPath = "c:\\QHHH";
if (!fso.FolderExists(sFolderPath)) {
    alert("Folder does not exist!");
    return;
}

fh = fso.CreateTextFile(sFolderPath + "\\myXML.xml", true);
//....
like image 169
Shadow Wizard Hates Omicron Avatar answered Mar 07 '23 11:03

Shadow Wizard Hates Omicron


To create a directory all you need is :

var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateFolder("fully qualified name of the forlder u want 2 create");
like image 44
Mohit Avatar answered Mar 07 '23 10:03

Mohit