Javascript: how to append data to a file

廉价感情. 提交于 2019-12-12 04:07:23

问题


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 :/


回答1:


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...




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/10193532/javascript-how-to-append-data-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!