如何使用 JavaScript 判断目录是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6940394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JavaScript to determine whether a directory exists?
提问by EMM
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?
我现在想要的是检查目录(我在上面的代码片段中指定的目录)是否存在?我想抛出异常或只是向用户显示“请指定要将文件存储到的目录”以及类似内容的警报。
所以我的问题是: 1.
是否可以检查指定的目录是否存在?
2.是否可以动态创建目录并自动将文件存储在那里?
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
请不要担心访问本地文件系统不好或其他任何事情。我是为我自己的个人使用而创建的,我很清楚这一事实。
请尝试用原生 javascript 回答,我没有使用 JQuery 或任何其他框架。
非常感谢
回答by Shadow Wizard is Ear For You
This should work:
这应该有效:
var sFolderPath = "c:\QHHH";
if (!fso.FolderExists(sFolderPath)) {
alert("Folder does not exist!");
return;
}
fh = fso.CreateTextFile(sFolderPath + "\myXML.xml", true);
//....
回答by Mohit
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");