am trying to read few lines from a txt file using JS,and i have this code but its not working for some reason,,
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\wamp\\www\\22.txt", 1, true);
var row = s.ReadLine();
alert(row);
any suggestions?!
Make sure your browser has the right permissions to perform that kind of operation. Usually, browsers won't allow direct file system access by default.
Only IE supports ActiveXObject. Trying to use ActiveXObject on any other browser will fail because there is no such variable defined.
You need to either limit yourself to IE, write a browser plugin instead, or give up trying to get file system access on other browsers and proxy files through a server instead.
If you're running WAMP anyway, just use standard AJAX to fetch the file 22.txt from the server. The easiest way is to use jQuery, where the code would be:
$.get("22.txt", function(data) {
alert(data);
}
You can search for how to do this without jQuery if you wish.
Related
I know that workers can't manipulate the document directly, but how about the DOM API methods? Where did they go?!
For example if I make a request that receives a HTML fragment, what I'm supposed to do if need just to parse it in order to retrieve some data from a specific node?!
There's absolutely no way to work with virtual DOM on web workers?!
Support in browsers
DOMParser or document.implementation are usually used to parse HTML to DOM in browsers. Neither is available in worker context.
In Firefox, this is not possible because someone decided there will be only one DOM parser instance for all threads. See this bug: https://bugzilla.mozilla.org/show_bug.cgi?id=677123
In google chrome it doesn't work either.
Workaround - external library
That's right, since browser developers didn't realize DOM and XML parsing will be one of main uses of WebWorkers, we'll have to fall back to external library. The best bet seems to be JSDOM, but you'll need to figure out how to browserify it.
Here's my failed attempt with DOMParser, I keep it for future experiments on this topic: https://jsfiddle.net/svaqb2wn/2/
You can use one of the DOM implementations running in a Web Worker:
Domino
JSDOM
XMLDOM
WorkerDOM
Via.js
At first you might think the proper way to go about parsing XML is XMLHttpRequest and in 9 out of 10 cases you would be right. However, in the current web worker spec we don't have access to XMLHttpRequest. An alternative is to use one of a few popular XML parsing libraries:
https://github.com/isaacs/sax-js
http://xmljs.sourceforge.net/index.html or https://www.npmjs.com/package/xmljs
HTML is just XML, so you can parse your data in this manner. An example using xmljs from npmjs above:
var XmlParser = require("xmljs");
var fs = require("fs");
var p = new XmlParser({ strict: true });
var xml = fs.readFileSync("./SOAP1.xml"); // XML in the examples direct
var xmlNode = p.parseString(xml, function(err, xmlNode) {
if(err) {
console.error(err);
return;
}
var nodes = xmlNode.path(["Envelope", "Body", "GetstockpriceResponse", "Price"], true);
console.log(nodes.map(function(n) { return n.text; }));
});
I've written this function to try and read a file located in the same directory as my Javascript files and index.html file. I've read from files before, but normally I have the user select the file themselves, so I've never had to create the actual file object.
Does anyone know why the code below doesn't work?
function getFile()
{
var reader=new FileReader();
var file=new File("input.txt");
var str=reader.result;
reader.readAsText(file);
return str;
}
Update:
Some additional information (My apologies if I don't answer your questions, I'm really new to this, and everything I know is self-taught).
Server side or client side? I think this it is going to be hosted serverside - I have a domain that I'm going to upload the file to.
Not possible due to security restrictions. You must use a file that was selected by a user. Imagine what would happen if javascript could read any file on your harddrive - nightmare!
I had a similar code for a desktop app written in JS. It worked well on IE and FF until Chrome came along (yes, it was a very long time ago!) and started restricting the sandbox ever more. At some point, IE and FF also tightened permissions and the method didn't work anymore (I used this code which does not work anymore):
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(filename);
if (file.exists())
{
inStream = Components.classes["#mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
inStream.init(file, 0x01, 00004, null);
sInStream = Components.classes["#mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
sInStream.init(inStream);
content = sInStream.read(sInStream.available());
}
} catch (ex) {
// and so on...
}
At some point FF and Chrome had some startup flags that enabled the sandbox to be lax on certain security restrictions, but in the end I realized that this is simply old code.
Today, I use localStorage to store data on the local machine. The only disadvantage is that you have to implement an import/export functionality so that it is portable to other browsers/machines by copy/paste the raw text.
What I do is simply this. The maximum size of the database is said to be about 10 MB (but deviations are known to exist) and all I store is a single JSON string:
function store(data)
{
localStorage.data = JSON.stringify(data);
}
function retrieve()
{
return JSON.parse(localStorage.data);
}
Obviously, these two functions are an oversimplification, you need to handle edge cases like when no data exists or a non-JSON string was imported. But I hope you get the idea on how to store local data on modern browsers.
With the File() constructor you can only create new file objects, but cannot read files from lokal disk.
It is not quite clear what exactly you want to achieve.
You say, that the input.txt is located in the same directory as your html and js. Therefore it is located on the server.
If you want to read a file from the server you have to use an ajax request which is already explained in anoter question.
i want to ask that if i want to rename a file in javascript, what can i do ? i have try a function which i see it online but cannot work.
function ChangeFileName()
{
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile("FilePath/MyFile.txt");
f.name = "MyFile.htm";
}
i search online and it says that the ActiveXObject is only available for IE and i intended to use it on mozilla because mozilla comes with ubuntu.
beside this, is there any method that i can rename a file inside the javascript ? thanks in advance for your help .
It is Javascript (in the browser), right?
If you run in the browser it is not allowed for security reasons. I think there is some way to do this using IE and ActiveX but using Pure Javascript I think it is not possible.
But you can do in JScript in the console, for example to delete a single file:
function MoveFile2Desktop(filespec)
{
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.MoveFile(filespec, "newname");
}
No, you cannot rename a file with javascript. Javascript is not able to interact with the user's computer in any way - it is only intended to be used to interact with the content of the web page it is rendered on.
JavaScript has no built in means to interact with a file system.
A host object might provide such a means.
The host object (window) that is available to JavaScript loaded from a web page in a typical web browser exposes no such object. Web pages are not allowed to edit the disks of people visiting their sites. (The exception is IE, with ActiveX, and some security warnings).
If you were running JavaScript in a browser extension or in a different environment (such as node.js) then it might be possible.
if (window.ActiveXObject) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\Program Files\\GM4IE\\scripts\\source.txt","C:\\Program Files\\GM4IE\\scripts\\target.txt", 1);
fso = null;
}
catch (e) {
alert (e.message);
}
}
I am getting error :
"Automation server can not create object" on the line where I am creating ActiveXObject instance.
I understand that it's considered very bad to access hard-drive data using javascript but I just need it.
I am using IE8 , Greasemonkey4IE to run my javascript.
Thank you,
Mohit
******************************
function WriteFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\source.txt","C:\\target.txt", 1);
}
I've put the above code inside a simple HTML page and it worked perfect.
http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm
You can find the similar code on above mentioned location.
I modified it a bit, tough.
But when I am trying to run it through GreaseMonkey4IE it simply spitting the same error I specified earlier.
I did it guys, but thanks a lot for your quick and helpful replies.
All I did is :
Go to Tools > Internet options > Security > Custom Level
Under the ActiveX controls and plug-ins, select Enable for Initializing and Script ActiveX controls not marked as safe.
Using native JavaScript, no, it is not generally possible to access a local file. Using plugins and extensions like ActiveX, Flash, or Java you can get around this rule, generally with some difficulty.
For some browser and OS specific exceptions to this general rule, you might want to have a look here:
Local file access with javascript
Note that as of late 2012, the FileReader API has been supported in all major browsers and provides a native JavaScript mechanism for accessing local files that the user nominates (via an input element or by dropping them into the browser).
This still cannot be used to access an arbitrary file by name/path as in the examples in the original question.
HTML5 File API has multiple ways to access local files.
window.requestFileSystem allows you to request access to the filesystem. Browser support is very poor on this (Chrome only).
FileReader is the HTML5 FileReader API that allows you to programatically read files that users select through a <input type='file' /> Browser support is better on this.
You should use fallbacks like flash and POST to a server for full file access.
Generally reading arbitary files is considered "cheating the browser" so I you'll either have to use secure HTML5, ActiveX or Flash. All 3 of those require user permissions.
After some research I have found:
var fso = new ActiveXObject("Scripting.FileSystemObject");
//This line will create a xml file on local disk, C drive
fh = fso.CreateTextFile( "C:\\fileName.xml", true);
fh.WriteLine("this is going to be written in fileName.xml");
This is how we can do it.There are other methods also.
Accessing local file system is very bad thing to do but yes we can do it.
Automation server can not create object
To get rid of this error go to Tools → Internet Options → Security → select Internet icon → click Custom level → select Enable for Initialize and script ActiveX controls not marked as safe for scripting.
I have not tested this on any other berowser except IE8, but I am sure it will work.
I asked how to check modify timestamps with BAT files and launch a command based on an if statement and Wimmel asked if I could use VBScript instead of Batch Files. I think this is a grand idea. This leads to another question
Can I access the VBScript functionality with JavaScript, while still being compatible Windows XP to Current? (specifically checking file modify timestamp and running a command depending on how recently modified)
Not sure that it is a good idea, but yes, you can use JavaScript (actually, JScript) instead of VBScript. Just use ActiveXObject class instead of CreateObject function that is used in VBScript to create objects.
Here is a code that reads the file modify timestamp using Windows Scripting and JScript:
var o = new ActiveXObject("Scripting.FileSystemObject");
var file = o.GetFile("c:\\temp\\test.js");
WScript.Echo(file.DateLastModified);
For more information, see JScript documentation and Windows Script Host documentation
Even though there are probably easier ways to achieve what you want to do, I had a go at trying the more theoretical part of your question, and apparently all the things we need are there.
Here is what I tried:
test.js:
WshShell = WScript.CreateObject("WScript.Shell");
var result = WshShell.Run("test.vbs", 0, true);
WSH.Echo(result);
test.vbs:
WSH.Echo "test.vbs"
WSH.Quit 5