PDA

View Full Version : Files in JavaScript ...



pcbrainbuster
03-22-2007, 09:03 PM
Hello :),

I was testing out a file opening writing and reading script that i made by myself and only the reading part does not work (for those of you dont know, javascript can create read and write files on a users computer and it can write it anywhere but it requires ActiveX) -

<html>
<body bgcolor="black" text="yellow">
<div align="center">
<input type="button" onclick="writef()" value="Create File"><br><br>
<input type="button" onclick="readf()" value="Read File"><br>
<textarea id="readfvalue" readonly style="width: 500px; height: 500px"></textarea>
<script>
function writef() {
var fso = new ActiveXObject("Scripting.FileSystemObject")
var fileo = fso.CreateTextFile("c:\\Documents and Settings\\pcbrainbuster\\Desktop\\text.txt", 1)
fileo.WriteLine("Hello I Like Eating Fruit Usually...")
fileo.WriteBlankLines(2)
fileo.WriteLine("Actually Always \:\)")
fileo.Close()
}

function readf() {
var fsob = new ActiveXObject("Scripting.FileSystemObject")
var fileob = fsob.CreateTextFile("c:\\Documents and Settings\\pcbrainbuster\\Desktop\\text.txt", 1)
document.getElementById('readfvalue').value=fileob.ReadAll()
fileob.Close()
}
</script>
</div>
</body>
</html>

Any ideas ?

codeexploiter
03-23-2007, 03:26 AM
From a web page point of view you can use the Activex technology for reading and writing files but this method has its own disadvantage it will work only on Microsoft Internet Explorer.

Normally this is a security risk (I mean trying to read and write files in your users machine) so most of the browsers doesn't support this feature.

pcbrainbuster
03-23-2007, 07:41 AM
Yeah thats true, it brings up a message that asks you if you are sure ...

BUt it has its own advantages too -
- Can write, read, move, delete and create files and folders in any directory

You can alos do so much more with this than cookies even, files like this are NOT cookies so they won't be deleted when the users delets them. They can be put ANYWHERE in the hard-drive, then you can read its value with ifs and elses and then create a great page with this...

What I need to know is -
1) What is wrongs with the code in the first post
2) What else can Activex do

Thanks :)

Bob90
03-23-2007, 01:46 PM
I think the problem lies with trying to create a file again not reading it in the read function.

You wrote


function readf() {
var fsob = new ActiveXObject("Scripting.FileSystemObject")
var fileob = fsob.CreateTextFile("c:\\Documents and Settings\\pcbrainbuster\\Desktop\\text.txt", 1)
document.getElementById('readfvalue').value=fileob.ReadAll()
fileob.Close()
}
Line 3 says to create a file! - you want to read a file. So you need something like

fileob = fsob.OpenTextFile("c:\\Documents and Settings\\pcbrainbuster\\Desktop\\text.txt").ReadAll();

Heres my ActiveX code I use. I wrote them myself (Probably after seeing someone elses).

//////////ACTIVEX SCRIPTING////////////
fso = new ActiveXObject("Scripting.FileSystemObject");
f=''

//create a file
function createFile(fileName, fileExt, fileLocation)
{
if(!fileName){return false}
if(!fileExt){var fileExt = ".txt"}
if(!fileLocation){var fileLocation = "" }//relative path

fileURL = fileLocation+fileName+fileExt;

if(!fso.FileExists(fileURL))
{
return null
}
else
{
f = fso.CreateTextFile(fileLocation+fileName+fileExt, false); // CreateTextFile(file_location [, over_write]) over_write = {true/false}
}

f.Close();
}

//return all content of a file if found
function returnFileContents(fileName, fileExt, fileLocation)
{
if(!fileName){return false}
if(!fileExt){var fileExt = ".txt"}
if(!fileLocation){var fileLocation = "" }//relative path

fileURL = fileLocation+fileName+fileExt;

if(!fso.FileExists(fileURL))
{
return null
}
else
{
f = fso.OpenTextFile(fileURL).ReadAll();
f.Close();
return f
}
}

//alter contents of file
function alterContentOfFile(fileName, fileExt, fileLocation, toDo, fileContents)//accepts strings and arrays as content
{
if(!fileName){return false}
if(!fileExt){var fileExt = ".txt"}
if(!fileLocation){var fileLocation = "" }//relative path

fileURL = fileLocation+fileName+fileExt;

if(toDo == "delete")
{
createFile(fileName, fileExt, fileLocation)
}
if(toDo == "add")
{
f = fso.OpenTextFile(fileURL);
f.WriteLine(fileContents)
f.Close();
}
}

//alert(eventz)
//////////////END ACTIVEX SCRIPTING//////////////
:)

pcbrainbuster
03-23-2007, 03:49 PM
Thanks for your post dude :), i did not even know i did that :), ok i will now edit my code and test it then will check out urs :)

pcbrainbuster
03-23-2007, 04:00 PM
Thanks IT WORKED !!!

But there is still one problem :(, the writing part of the script adds two blank lines to the txt file but when i read it instead of being like this -

Hello I Like Eating Fruit Usually...


Actually Always :)

How it is supposed to be, it turns out like this in the textbox -

Hello I Like Eating Fruit Usually... Actually Always :)

And i can't seem to understand whats wrong, so your help would be appreciated :)

pcbrainbuster
03-23-2007, 05:14 PM
Please help me :( (i am crying in real life :()

Bob90
03-23-2007, 05:39 PM
Just remove
fileo.WriteBlankLines(2) Thats what's adding the blank lines!


I have updated my activeX file functions to make them work better

//////////ACTIVEX SCRIPTING////////////
//create a file
function createFile(fileName, fileExt, fileLocation, overWrite)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");

if(!fileName){return false;}
if(!fileExt){var fileExt = ".txt";}
if(!fileLocation){var fileLocation = "";}//relative path
if(!overWrite){var overWrite = false;}

fileURL = fileLocation+fileName+fileExt;

if((!fso.FileExists(fileURL))||(fso.FileExists(fileURL)&&overWrite))
{
var f = fso.CreateTextFile(fileURL, overWrite); // CreateTextFile(file_location [, over_write]) over_write = {true/false}
f.Close();
return true;
}
else
{
return null;
}

fso = null;
f = null;
}

//return all content of a file if found
function returnFileContents(fileName, fileExt, fileLocation)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");

if(!fileName){return false}
if(!fileExt){var fileExt = ".txt"}
if(!fileLocation){var fileLocation = "";}//relative path

fileURL = fileLocation+fileName+fileExt;

if(!fso.FileExists(fileURL))
{
return null;
}
else
{
var f = fso.OpenTextFile(fileURL,1)
var txt = f.ReadAll();
f.Close();
return txt;
}

fso = null;
f = null;
}

//alter contents of file
function alterContentOfFile(fileName, fileExt, fileLocation, toDo, fileContents)//accepts strings and arrays as content
{
var fso = new ActiveXObject("Scripting.FileSystemObject");

if(!fileName){return false}
if(!fileExt){var fileExt = ".txt"}
if(!fileLocation){var fileLocation = "";}//relative path

fileURL = fileLocation+fileName+fileExt;

if(fso.FileExists(fileURL))
{
if(toDo == "delete")
{
createFile(fileName, fileExt, fileLocation);
}
if(toDo == "add")
{
var f = fso.OpenTextFile(fileURL,8);
f.WriteLine(fileContents);
f.Close();
return true;
}
}

fso = null;
f = null;
}

//http://4umi.com/web/javascript/fileread.htm
//////////////END ACTIVEX SCRIPTING//////////////

pcbrainbuster
03-23-2007, 05:52 PM
No no no :) You got it all wrong,

Thats supposed to happen. In the textarea the blank lines from the text file do not show and i simply don't know whats wrong instead it shows the first and second part together :(, so the text file has this layout inside it -

sentence 1
blank
blank
sentence 2

But the textarea thing shows it like this -

sentence 1 sentence 2

But i need it to be in the file's format.

Thanks :)

Bob90
03-23-2007, 06:38 PM
Just change .innerHTML to .value
It seems to keep the formatting.
:confused: Can't tell you why though.

pcbrainbuster
03-23-2007, 06:39 PM
Ok thanks i will try it :) and report back :)

pcbrainbuster
03-23-2007, 06:42 PM
Hmmm it seems to work for some reason :confused:...

DO you mind helping me find out why on the internet? :)

Bob90
03-23-2007, 06:43 PM
I think you're good enough to find it yourself :)

pcbrainbuster
03-23-2007, 06:45 PM
Ok thanks anyway :( and :) (mixed moods)

Bob90
03-23-2007, 06:52 PM
As there is no public specification for this property, implementations differ widely. For example, when text is entered into a text input, IE will change the value attribute of the input's innerHTML property but Gecko browsers do not.

It should never be used to write parts of a table—W3C DOM methods should be used for that—though it can be used to write an entire table or the contents of a cell.
http://developer.mozilla.org/en/docs/DOM:element.innerHTML

pcbrainbuster
03-23-2007, 07:36 PM
I still don't understand :(

jscheuer1
03-23-2007, 08:31 PM
I still don't understand :(

What part of 'only works in IE' don't you get?

pcbrainbuster
03-23-2007, 08:53 PM
I ALREADY KNOW THAT !!!

If you read the whole thread you would have realized that I do not understand why the textarea only shows the correct format of the text documents if its thing in javascript is value and not innerHTML...

Why did you get so worked up about that thing i said above? :(

jscheuer1
03-23-2007, 09:06 PM
You are the one who is worked up my friend. I'm frankly surprised that innerHTML works in any browser for a form element. However, since the textarea tag is constructed more like block or inline elements that accept text between open and close tags, I am not entirely surprised.

pcbrainbuster
03-23-2007, 09:09 PM
Mind explaining inline and block elements and what they have against innerHTML :) (sorry for the huge dose of questions but for some reason i did not pay attension to things like this when i was learning, very sorry though :()

jscheuer1
03-23-2007, 09:19 PM
I think you misunderstood. The typical block level elements <p> and <div> accept text between their open and close tags and have the innerHTML property. So does the inline element <span>. However, typically form elements are both inline and self closing so, there isn't anywhere for them to have innerHTML. As far as I know, giving this property to <textarea> is only done in IE. This is likely because it is a form element. IE does many things that are not part of the standards. If you become somewhat familiar with javascript and/or HTML you will see a pattern emerge. We do it this way in all browsers except in IE it is done that way. However, IE is slowly catching up, it now behaves in many ways that are according to standards yet, often also still retains its proprietary methods.

The bottom line in forms though is that the innerHTML property is very tricky and even when it appears to work in all browsers, which it can in certain circumstances, it is the least reliable way to use javascript with forms. Data can be easily lost. If you use the value property or manipulate form elements using the DOM, results are much more reliable.

pcbrainbuster
03-23-2007, 09:26 PM
Ahhh I see so are you saying that block elements work with innerHTML while inline elements work with value ?

Also you have told me above about innerHTML and value but did not explain what inline and block elements are ...

Another thing is that in my test (the file thing) i replaces textarea with span but for some reason it did not work with innerHTML eigther. Was this expected by you ?

jscheuer1
03-23-2007, 09:55 PM
The distinction between value and innerHTML is more between form elements (use value) and other elements (use innerHTML, if they have it). An image obviously has no innerHTML or value for example. So mostly it is the self closing tags that do not have innerHTML and also all form elements except in IE where textarea (a form element) does have innerHTML. Strictly speaking, innerHTML is only for situations like so:


<div><a href="some.htm"><img src="some.jpg"></a>Some text</div>

The red is the innerHTML of the div. It will show a div containing a linked image and some text. It gets confusing partly because it can be used for:


<div>Some text</div>

Which looks just like:


<textarea>Some text</textarea>

But, there the property containing the red part is known as the textarea's value. If it looked like so:


<textarea><a href="some.htm"><img src="some.jpg"></a>Some text</textarea>

The contents of the text area would show no image and would not be linked, it would just show the code. So, it is its value not its innerHTML.

pcbrainbuster
03-23-2007, 10:03 PM
Is this what you are saying -

Anything that has text between a tag and it's close tag is innerHTML while anything that has a closing tag within itself is value and the last one was a little but un-understandable but i am thinking that anything that does not accept other tags is also value...

If this is all true then why in my other test span tag do the same a textarea ?

jscheuer1
03-24-2007, 02:19 AM
I think you are getting it. One thing to remember is that this is all one part logic and another part convention. You can understand the logical part but, the conventions simply are what they are. There is also a third part confusing things a bit in that any particular browser will try to understand what you are doing even if it is invalid (unconventional) and/or flies against logic so, the results that you get in any given browser may not translate to others. IE is usually the odd bird in all of this but, sometimes other browsers will surprise you with their own quirks.

That said, the last part I was trying to convey is that, strictly speaking, unless it parses as HTML, it cannot strictly be innerHTML. That's the case with textarea. If you place valid HTML code between the opening and closing tags of a textarea element, it is parsed as text, not as HTML.

pcbrainbuster
03-24-2007, 11:20 AM
Hmmm I see THANKS :),

but if this is all true then why does my span tag (eg <span></span>) not showing the correct format of the text file ???

pcbrainbuster
03-24-2007, 11:22 AM
Maybe it could be because the activexobject filesystemobject will only accept value as it's data host (if you know what i mean)...

DO you think thats the case ?

jscheuer1
03-24-2007, 12:07 PM
Looking back over the thread, it is unclear to me what exact code you are currently using. I can easily say that if you are importing HTML code to a span element via its innerHTML object or the DOM, if that HTML code includes tables, paragraphs, divisions, any element that isn't inline - it is producing invalid HTML. That is because a span is an inline element and these should never contain anything other than text or other inline elements.

Many browsers will let you get away with it but, many will not or at least the rendering may be other than expected. The div element is the ideal container to write to but, even then - if the HTML code you are placing inside it is invalid, there could still be rendering problems.

A handy way to check the results of your code is to, after you have run it, paste this into the address bar:


javascript:document.write('<textarea>'+document.body.innerHTML+'<\/textarea>')

Hit enter. Then right click on the textarea, select all, copy and paste into your text editor. This will show you the HTML code that the browser has generated from your markup and script and often will show why the browser is having trouble rendering it as you intended.

Note: After performing the above procedure, hit the back button and then refresh to return to normal browsing.

pcbrainbuster
03-24-2007, 01:07 PM
Thanks for that info but since i had no answer for what inline and block elements are will have to show you my script and here it is -

<html>
<body bgcolor="black" text="yellow">
<div align="center">
<input type="button" onclick="writef()" value="Create File"><br><br>
<input type="button" onclick="readf()" value="Read File"><br>
<span id="readfvalue"></span>
<script>
function writef() {
var fso = new ActiveXObject("Scripting.FileSystemObject")
var fileo = fso.CreateTextFile("c:\\Documents and Settings\\pcbrainbuster\\Desktop\\text.txt", 1)
fileo.WriteLine("Hello I Like Eating Fruit Usually...")
fileo.WriteBlankLines(2)
fileo.WriteLine("Actually Always \:\)")
fileo.Close()
}

function readf() {
var fsob = new ActiveXObject("Scripting.FileSystemObject")
var fileob = fsob.OpenTextFile("c:\\Documents and Settings\\pcbrainbuster\\Desktop\\text.txt", 1)
document.getElementById('readfvalue').innerHTML=fileob.ReadAll()
fileob.Close()
}
</script>
</div>
</body>
</html>

See anything wrong ???

jscheuer1
03-24-2007, 01:51 PM
After looking at your code, I don't think the difference between inline and block level elements is at issue here. It is a rather basic concept in web design though. With exceptions, basically an inline element has no width or height and does not produce a hard line break. Block level elements do.

On to your code. Works just fine here (IE only). If you were expecting to see 2 blank lines after:


Hello I Like Eating Fruit Usually...

That won't happen even in regular HTML, ex:


<span>Hello I Like Eating Fruit Usually...


Actually Always :)</span>

will render like so in any browser:

Hello I Like Eating Fruit Usually...Actually Always :)

pcbrainbuster
03-24-2007, 02:35 PM
Wow I did not even think about that !!!
Anyway how can you write it in its own correct format ?

Any ideas?

jscheuer1
03-24-2007, 02:52 PM
Well, the format is technically correct. You could put <br> tags into the text file where desired.

pcbrainbuster
03-24-2007, 02:53 PM
Ok I will try that and post back ...

pcbrainbuster
03-24-2007, 03:07 PM
Hmm well it works but i am just a little sad about the whole value and innerHTML thing...

jscheuer1
03-24-2007, 03:18 PM
Well cheer up. It's like getting down about the weather, nothing you can do about it and it will probably change. In the case of value and innerHTML though the change is likely to be quite a ways off.

You should take heart that your code works even though it is limited to IE.

I did play around with it a little more (using the paste into the address bar method I mentioned before) and I discovered that the browser is writing the innerHTML property without the line breaks. It is permitted to do this because they technically have no meaning in HTML and it is, after all, innerHTML. This breaks down with the pre tag though which does support line breaks. In that instance it would be a quirk of the browser.

pcbrainbuster
03-24-2007, 03:30 PM
Thanks :),
but now i wish to know two other things -

1) In areas like at the top of this page there is a search box and it has some of it "cut off", how is this done?

2) Can javascript append or prepend to a file?

jscheuer1
03-24-2007, 03:52 PM
Nothing is cut off, what you see is part of this background image:

http://www.dynamicdrive.com/forums/designfiles/rightcorner.gif

I don't know about appending and prepending text to a file except that using the methods you've already, it wouldn't be javascript per se anyway, it would be activeX and I would imagine so. If nothing else you could read the file to a variable, append and/or prepend to it, then write it all back to the file (overwriting what was originally there).

pcbrainbuster
03-24-2007, 03:55 PM
Yeah I guess I will have to find more info on the web...