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
This should work:
var sFolderPath = "c:\\QHHH";
if (!fso.FolderExists(sFolderPath)) {
alert("Folder does not exist!");
return;
}
fh = fso.CreateTextFile(sFolderPath + "\\myXML.xml", true);
//....
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");
Related
I am working with Angular 5, I have an application in which I need to read an AMP HTML file as text. This file is contained in a component and should only be accessed from this component.
I would like to be able to open the file in read-only by giving its name.
I'm actually searching for something like this:
let file = open('amp.html');
Is it possible? If not how can I do to achieve this?
If you're writing browserside JS
You can't just simply read a file. The JS is running on your browser, and you need to think about where you're getting that file from.
If the file is on a server, you need to fetch that file from the server first by making a request for it.
If you're reading a file on the user's computer, you're gonna be using the File API on the browser to allow the user to select that file.
If you're writing backend JS
Assuming you're using NodeJS, you can conduct file operations like you would with other programming languages. Check out the fs module
If i understand you correct, you can read it as text like this:
function readFile(file){
var raw = new XMLHttpRequest(); // create a request
raw.open("GET", file, false); // open file
raw.onreadystatechange = function (){ // file is ready to read
if(raw.readyState === 4){
if(raw.status === 200 || raw.status == 0){
var allText = raw.responseText;
alert(allText); // can be also console.logged, of course.
}
}
}
raw.send(null); // return control
}
usage:
readFile('link.html')
I solved this issue thankfully to this question.
I am having trouble writing to a file in Titanium Studio.
specifically .json file. Code is compiled through and no exception was thrown.
Here is my relevant section of code, I parse the file to var first before adding element and stringify it to be written back.
Reading works perfectly, so is adding element, it's the writing process that has issues
var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var jsontext = file.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
"picloc":imagename,
"title":titlef.value,
"desc1":descf1.value,
"desc2":descf2.value,
"desc3":descf3.value
});
jsontext = JSON.stringify(jsondoc);
file.write(jsontext); // write(data,[append])
Note: I have consulted Documentation and done some of my own search, some are suggesting that "Filestream" should be used in place of normal file along with .close(), I have yet got them working but it could be pointers the solution, if anyone knows how to get it working
Thanks in advance.
EDIT: This question is flagged for duplication, initially I deemed that was 2 separate issues, one was about merely writing text to a file. Another is parsing event.media (picture) into a file.
I got it working now, The issue was that I was trying to write to file in read-only directory
Ti.Filesystem.resourcesDirectory: A read-only directory where your application resources are located
Ti.Filesystem.applicationDataDirectory: A read/write directory accessible by your app. Place your application-specific files in this directory.
The contents of this directory persist
until you remove the files or until the user uninstalls the application
Here is my code, directory is modified
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = sesfile.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
"picloc":imagename,
"title":titlef.value,
"desc1":descf1.value,
"desc2":descf2.value,
"desc3":descf3.value
});
jsontext = JSON.stringify(jsondoc);
sesfile.write(jsontext,false);
If you are unable to locate data directory and simply want to load the file from there.
(In my case it does not exist in project nor will be created with Webpreview compilings)
You can do bootstrap-ish type instruction like this first
var rdfile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = rdfile.read().toString();
var jsondoc = JSON.parse(jsontext);
sesfile.write(jsontext);
hope it helps whomever makes amateur mistake like I did.
how can i append data to a file using javascript?
i tried to use this code, but i got an error:
var fso = new ActiveXObject("Scripting.FileSystemOject");
var filepath = fso.GetFile("member.txt");
var fileObject = fso.OpenTextFile(filepath, 8);
file.WriteLine(id + "|" + pass);
fileObject.close();
the error is on var fso = new ActiveXObject("Scripting.FileSystemOject");, written: Error: Automation server can't create object
is there any other way to append the file using javascript or the way to fix this? thanks :)
EDIT:
i have doing what's written on this, and it still not working :/
I just realized these in your code:
var fileObject = fso.OpenTextFile(filepath, 8,true);
You'll need the true-argument, if the file does not exist, or you want to overwrite/append it.
var filepath = fso.GetFile("member.txt");// This won't work.
var filepath = "your_filePath"; // Use this instead
var fileObject = fso.OpenTextFile(filepath, 8, true);
OpenTextFile() needs a path as a string like "D:/test/file.txt". GetFile() returns an object, which you can see as a string (D:\test\file.txt), but it's not a string. Use also absolute paths, relative paths don't seem to work by my experience.
EDIT
Add the code below to the <head>-part of your html-file, then save locally as a hta (with file extension hta, not htm or html).
<hta:application
applicationName="MyApp"
id="myapp"
singleInstance="yes"
/>
Then run the hta-file. If you still getting an ActiveX-error, it's not supported by your OS. If this works, you haven't done all the security settings correct.
EDIT II
In this case it's not very usefull to get the path through ActiveX, you'll need to write it literal anyway. And I'm not supposed to do your homeworks, but this does the trick...
var filepath = new String(fso.GetFile("member.txt")).replace(/\\/g,'/');
And don't forget what I've said above about using absolute paths...
The 8 in the OpenTextFile function specify that you want to append to the file. Your problem comes from the security restriction of your browser. To make it work you'll have to lower the security level, which is not really recommended.
The error is thrown because there are security restrictions which donot allow the activex to run. change your security settings to allow the activex if your using internet explorer (which i think you are).
This might be useful http://windows.microsoft.com/en-US/windows/help/genuine/ie-activex
Cheers
EDIT: i have doing what's written on this, and it still not working :/
* try Restarting your browser
As pointed out in this comment
Javascript: how to append data to a file
the cause of the error Error: Automation server can't create object is the typo in the progid passed to ActiveXObject: Oject instead of Object:
var fso = new ActiveXObject("Scripting.FileSystemOject");
there is a missing b!
this is my problem i cant save my results to driver x that is company shared folder and i have permission to write for some reason , but i can save on driver c.
the messege show
Webpage error details
Message: Automation server can't create object Line: 93 Char: 1 Code:
0 URI:
file:///X:/OmrilDocs/Omrix%20Public/All%20Omrix%20Public/Training/index.html
notic : i can use only javascript , no server side language is allowd :(
this is the code i use
alert(answerText);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("X:\OmrilDocs\Omrix Public\All Omrix Public\Training\text.txt", true);
s.WriteLine(answerText);
s.Close();
im using ie8 on xp 2
You need to replace \ with \\.
It should look like:-
var s = fso.CreateTextFile("X:\\OmrilDocs\\Omrix Public\\All Omrix Public\\Training\\text.txt", true);
While it is running, it gives a popup window which you need to allow to create the file.
Screenshot look like:-
Eventhought you've loaded index.html from server, the code is executed in the work station.
You've written the path literally in your function. However, FSO tries to find the target from the work station only, and it is not capable to follow a path associated to some drive letter. (In other work stations that same path might be associated to a different letter.)
So, you need to to use the real name (or IP) of that server:
fso.CreateTextFile("//YOUR_SERVER_NAME/OmrilDocs...
Also the saving folder have to exist. When using true-argument in CreateTextFile only a new file is created to the provided path, new folders are not. Hence if there is a misstypo in the pathname, function will fail.
I am trying to create a file on the local machine which captures the var file in javascript.
<script>
function button_click()
{
var file = GetFile('Getdoc'.aspx');
WriteToFile();
}
function WriteToFile() {
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.CreateTextFile("C:\\Test\\Logfile.txt");
s.Write(file1);
s.Close();
}
</script>
Here we get a httpresponse stream which contains data in bytes into var file.
If I could find some help on this would be appreciated.
Thank you.
If I understand you correctly, you are encountering a problem when you are trying to write a file using ActiveXObject on IE? There is two things wrong with your script.
var file = GetFile('Getdoc'.aspx'); should be var file = GetFile('Getdoc.aspx');
You do not have file1 defined, so it is writing nothing to the file.
You need to keep in mind that most versions of IE have this functionality disabled due to the huge security risk that this poses.