How to use FileSystemObject to read file in JavaScript - javascript

I want to read a file with FileSystemObject. My code is as following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Read json</title>
</head>
<body>
<script type="text/javascript">
function readFile(filename){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1;
var f1 = fso.OpenTextFile(filename, ForReading);
var text = f1.ReadAll();
f1.close();
return text;
}
myJSONText = "text.txt";
var myObject = readFile(myJSONText);//eval('(' + myJSONText + ')');
document.write(myObject.name);
</script>
</body>
</html>

First, let me repeat some comments above. I've never seen using ActiveXObject client side extolled as a thing that should be done.
Now, let me say I'm trying to learn how to do this myself. Here are some thoughts (and helpful links, see the bottom) on this question.
The general layout, according to "Much ADO about Text Files" on MSDN's scripting clinic column, is:
Create the object.
Create another object, using the first, that uses
a method of the first object (such as getting a file).
Do things to
the file.
Close the file.
How do you start? According to IE Dev Center (linked here), use an ActiveXObject in Javascript as follows:
newObj = new ActiveXObject(servername.typename[, location])
You've got that when you declare fso in your code. What about this "servername" thing, isn't the file accessed locally? Instead of "servername etc" you've put in Scripting.FileSystemObject. This is actually fine, if the HKEY_CLASSES_ROOT registry key on the host PC supports it (see ref above).
Once the ActiveXObject is successfully declared, and if the browser allows it (IE only), and if the end user agrees to any warnings that pop up ("An ActiveX control on this page might be unsafe to interact with other parts of the page..." etc), then the object allows you to use any of the methods associated with that object. That's where the power of the Windows Scripting FileSystemObject comes into play.
Any FileSystemObject (fso) method is now available to use, which as its name suggests, means file (and directory) interaction on the local machine. Not just reading, as your question is focused on, but writing and deleting as well. A complete list of methods and properties is available at MSDN here. After being used, close out the file using the .close() method.
So, this is dangerous for obvious reasons. But what wasn't obvious to me at first was that these interactions with the filesystem may happen invisibly. There is a good chance that whatever you do, from reading a file to deleting a directory tree, no warnings or command prompts will come up to let you know what's happening because of your few lines of code.
Let me finish by commenting on the last bits of code above. Using JSON in conjunction with data pulled from the FileSystemObject provides a great way to allow JavaScript interaction (JSON .parse and .stringify come immediately to mind). With this, data could be stored locally, perhaps as an alternative to HTML5 local storage (ref this SO thread, which goes more in-depth with this concept, and another SO question I raised about this here).
Here are some links for further reading:
IE Dev Center, JavaScript Objects, ActiveXObject
MSDN JScript Windows Scripting (including FileSystemObject methods, etc)
MSDN Scripting Clinic (older articles, many broken links, but stil a lot of good info on this stuff)

Related

Google Apps Script: Referencing the ActiveXObject

I wish to create an Excel object from within App Script. The following resource:
http://www.webdeveloper.com/forum/showthread.php?249479-Javascript-excel-object
shows how to do so using Javascript - I was therefore hopeful that I could use this code within Google Apps Script:
function xlTest() {
var xls = new ActiveXObject ( "Excel.Application" );
var newBook = xls.Workbooks.Add;
newBook.Worksheets.Add;
newBook.Worksheets(1).Activate;
}
When I try to run this function I get the error message:
ReferenceError: "ActiveXObject" is not defined
Hopefully I simply need to add a reference to ActiveXObject, if so could somebody please advise how I add a reference to ActiveXObject from Google Apps Script? Many thanks!
The question has nothing to do with Google Apps Script (or even JavaScript) and should not be tagged as such. You can't simply throw this code into Google Script Editor and expect things to work.
GAS is a JavaScript-based runtime that lives on Google servers, not in your browser. It doesn't have access to BOM (Browser Object Model) Furthermore, ActiveX is not supported in most browsers, including Microsoft Edge. Of course, VBA methods like Sheets.Add won't work for obvious reasons.
If you log the global object in Script Editor, you'll see all of its properties available to you as a developer.
In your browser, the properties of global object will be different:
Please take the time to go through GAS documentation and understand features & limitations https://developers.google.com/apps-script/

ActiveXObject javascript Events

I want to utilize events from the IE activex object and can't seem to get it to work.
Please see code below and lemme know if any idea's come to mind:
<html>
<head>
<title>Automate IE</title>
<script type="text/javascript" language="javascript">
var ie = new ActiveXObject( "InternetExplorer.Application" );
[...some calls to ie functions...]
</script>
</head>
<body>
This is a test for IE automation.
</body>
Now I want to be able to use events for the 'ie' object as listed here:MSDN IE Events
But can't seem to get it to work...I tried the following solutions (none worked):
Approach 1:
1. eval( "function ie::EventName(){return MyCustomEvent()}" ); - no joy )-:
Approach 2:
2. <script for="ie" event="EventName">some code here</script> - still no joy )-:
This file is saved with the 'HTA' extension - and runs with the MSHTA scripting host
Any advise \ help on how to do this would be much appreciated...thanks!
I've had success with your first method (see here).
From my experience, the parameters of the function definition must exactly match those of the event definition, e.g. for the BeforeNavigate2 event:
function ie::BeforeNavigate2(pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel) {
/* do stuff here */
}
Virtually all the Internet Explorer Application events take some parameters, and therefore your eval doesn't work.
(It's probably self-evident, but you have to fill in the actual event name; you cannot call the function whatever you want.)
I would have answered your question sooner but I had two kids in the last three years ;)
I don't think it is possible in an HTA anymore. ActiveXObjects have never supported events in JScript. Before IE11 you could have used VBScript and CreateObject(object, event_prefix) to register event hooks - https://msdn.microsoft.com/en-us/library/xzysf6hc(v=vs.84).aspx (And you only need to register the events in VBScript because the VBScript variables can be accessed in JavaScript.)
If IE<11 is not an option you'll need to use WScript/CScript. Here is a gist for example: https://gist.github.com/subzey/4374329
Executing WScript from an HTA is feasible with the WScript.Shell activex object, but don't get your hopes up because there is no analogous WScript.CreateObject ActiveX object (or anyway to access CreateObject() from JavaScript/JScript.)
To achieve what you want, you'd need to wrap your IE logic up in a WScript/CScript host script that monitors (or polls) a file on your hard drive. Then your HTA application can write commands to that file. If you need a feedback loop your HTA could monitor a command-result file that gets updated when the JScript logic finishes.
I've been a proponent of HTA's since the 90's, and I still use them for personal quick and dirty projects, but the writing is on the wall about their longevity. There are already a bunch of bugs related to the host window since IE10 and Microsoft has confirmed they won't be fixed.
Given that, you might want to investigate Electron as an alternative if you were not relying on IE-specific functionality: http://electron.atom.io/docs/v0.27.0/api/browser-window/

Using JavaScript to "Create" a Microsoft Word Document

I would like to dynamically create a document using JavaScript and then open that document in Microsoft word. Is this possible? Here is my current code:
<html>
<head>
<title></title>
<script src="js/jquery-1.4.4.js" type="text/javascript"></script>
</head>
<body>
<div id="myDiv">The quick brown fox jumped lazly over the dead log.</div>
<script type="text/jscript">
var printWindow = window.open("", "Print", "width=800,height=400,scrollbar=0");
var printAreaHtml = $("#myDiv").attr("outerHTML");
printWindow.document.open("text/html", "replace");
printWindow.document.writeln("<html><head>")
printWindow.document.writeln("<meta HTTP-EQUIV='Content-Type' content='application/vnd.ms-word'>");
printWindow.document.writeln("<meta HTTP-EQUIV='Content-Disposition' content='attachment;filename=print.doc'>");
printWindow.document.writeln("</head>");
printWindow.document.writeln("<body>");
printWindow.document.write(printAreaHtml);
printWindow.document.writeln("</body>");
printWindow.document.writeln("</html>");
printWindow.document.close();
// printWindow.print();
</script>
</body>
</html>
I'm not sure exactly what you are trying to do in your code up there but here is some information i found about accessing a word document and a table within the doc:
Microsoft Word Object Model
This object model is part of Microsoft Word (not Javascript) and it lets you "automate" word remotely from other programs (not just web pages, but any computer program).
It is primarily designed for Visual Basic, but can be accessed by Javascript from a web page - see para 2 below.
However it is a bit more tricky to use through Javascript, particularly because you cannot use visual basic constants - you need to refer to them by value. If you research this further, you will soon know what I mean by this.
So where can you find out about this Object Model?
It is all there in the Word help files if you look for it.
If you look in the Word help, under programming information, you will find the Microsoft Word Visual Basic Programming Reference.
The Word object model, which lets you do things you will need to solve your problem like:
Open Word
Open a Document in Word
Access the collection of Tables in that ActiveDocument.
Access the Rows and Cells of a given Table.
How do you access this from Javascript?
This might only be done I think through Internet Explorer (and perhaps Opera).
Here you need to learn about ActiveXObjects.
ActiveXObjects (if you do not know) are separate computer programs which enable additional functionality. There are lots of ActiveX objects on the internet.
When you install Word, this also installs an ActiveX object for automating word, giving you access to the Word Object Model.
So in javascript, lets open up a new instance of word:
var oApplication=new ActiveXObject("Word.Application");
oApplication.Visible=true; // "Visible" is in the Word Object Model`
There you have it.
Then if you want to open you file and get the table:
oApplication.Documents.Open("myfilename");
var oDocument=oApplication.ActiveDocument;
var oTable=oDocument.Tables(1);`
And now I leave it to you to keep going with the rest.
EDIT: this wasn't possible when the question was asked but in 2017 it is. See link from comment by jrm - http://www.effectiveui.com/blog/2015/02/23/generating-a-downloadable-word-document-in-the-browser/
Browser place some serious restrictions on Javascript which will prevent you creating a downloadable file. See this related question:
Create a file in memory for user to download, not through server
I don't believe that this idea will work. You need to create the Word file with a serverside language. For example PHP: http://www.webcheatsheet.com/php/create_word_excel_csv_files_with_php.php
You can not get this working using client side. Main thing is you need to send headers not as html. So I would suggest you to use server side scripting as Max suggested and preferably use .htaccess file if you are using Apache server to also name these files as .doc.
Lets assume your php file needs to create a .doc file with some passed argument lets say id. So you want file_.doc to point to file.php?id=, try using following rewrite rule so that browser understands by extension too
RewriteRule file_(.*).doc file.php?id=$1
if you need server side document generation and server is running Java, take a look at this:
https://github.com/leonardoanalista/java2word/
This is absolutely possible. Googoose is a jQuery plugin that I wrote to handle a lot of the more complicated conversions. It's still fairly new, but there appear to be a few other attempts at this, so you could check those out. Here is the best documentation I've found so far that actually explains this process http://sebsauvage.net/wiki/doku.php?id=word_document_generation. If you're interested check out the examples in Googoose.
sometimes we can not use server side app or activeX to create office document because of phonegap mobile app that uses only client-side javascipt to operate.
the only way i found for now is uding word binary file format or OOXML
http://msdn.microsoft.com/en-us/library/hh643138(v=office.12)
some say that its much easier to create RTF file and i agree with them.

Outlook 2010: How to compose e-mail from VBScript/JScript

I have some JScript code I have been using for a few years which is able to read an XML file and open an Outlook compose window with the to/cc/subject fields prepopulated and files pre-attached based on the XML data. The user can then attach more files, make any corrections and send the e-mail. The core part of the code uses CDO to create the new message:
var ol = WScript.CreateObject("Outlook.Application");
var msg = ol.CreateItem(olMailItem);
Unfortunately I have just discovered this no longer works with Outlook 2010 64-bit as CDO is no longer supported. The suggestion from Microsoft is to update your applications to use the Outlook object model instead, but I can't find any examples at all of how I might use the Outlook object model to open a compose window from either VBScript or JScript. All the "VB" examples on MSDN produce syntax errors when run through the VBScript interpreter.
Can anyone point me to any short examples demonstrating how to interface with Outlook 2010 using either VBScript or JScript?
EDIT: Just realised the problem is that I'm using MAPI.Session to adjust attachment properties and this is what's failing. I guess I need to find what this has been replaced by:
var oSession = WScript.CreateObject("MAPI.Session");
oSession.Logon("", "", false, false);
var oMsg = oSession.GetMessage(strMsgID);
var oAttachFields = oMsg.Attachments.Item(i+1).Fields;
...
Ok, turns out most of the MAPI.Session stuff has been merged in with the actual objects, which are still accessible using the first bit of code in my post ("Outlook.Application"). I was only using the MAPI.Session stuff to hide image attachments (so they can be shown inline in the message body, and not as files attached to the e-mail) but this now seems to be incorporated automatically.
So all I actually had to do was remove the MAPI.Session stuff and then everything started working. I will post a link to the code shortly in case anyone else finds it useful.
EDIT: Here is the code on GitHub if anyone is after a relatively simple example.

Tutorial for using JavaScript on a Desktop

I need to do some scripts in java script.
I am working on it but couldn't find a few solutions to a few problems.
First of all I need a GOOD tutorial, but not for an internet page but for a DESKTOP script.
Things couldn't find out like :
1) I wanted a simple message box in order to debug my program, I used:
var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
2) Couldn't find how to open a file
Based on your comments, I guess that you are attempting to run a JavaScript file directly on Windows. Double-clicking on a .js file in windows will (probably) run it in Windows Script Host.
The prompt() function will not work this way, since WSH provides a completely different API than browser-embedded engines.
The following code should accomplish your intentions. However if you want anything more than a simple popup, HTAs are the only way to do complex GUIs with JScript on the desktop.
var fso, ws, ts;
fso = new ActiveXObject('Scripting.FileSystemObject');
ws = WScript.CreateObject('WScript.Shell');
var ForWriting= 2;
ts = fso.OpenTextFile('foo.txt', ForWriting, true);
ts.WriteLine(new Date().getTime());
ts.Close();
ws.Popup('Wrote to file!');
var ForReading= 1;
ts = fso.OpenTextFile('foo.txt', ForReading, false);
var fileContents = ts.ReadLine();
ts.Close();
ws.Popup('The file contained: ' + fileContents);
WScript.Quit();
I have to ask: why is JavaScript the right tool for the job? Why not use a scripting language intended to be used this way, such as Python, Ruby, Lua, ... etc?
If you are using Microsoft's JScript (and it sounds like you are), look to the MSDN web site for help. The page here looks fairly good. Google can also help with that.
Assuming you don't mind using Java, you could also use the Mozilla Rhino shell. But it doesn't look like there is a standard way of reading from the console in JavaScript. (presumably since this is not something typically required in a JavaScript application...) The built in JavaScript functions in the shell seem fairly basic, but you can read a file.
There area also examples of using Rhino, which may be helpful. You can interface with the Java API to do whatever else you need to do.
Edit: I wrote this answer a long time ago; today I would use node.js. See their learning page.
The latest prerelease of Opera acts as a runtime for JS applications.
They have tutorials describing how to use it.
I used: var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
Presumably your runtime doesn't implement prompt that in a way that is compatible with those arguments.
2) Couldn't find how to open a file
This depends on the runtime you use. JS itself doesn't have anything built in to read files (or display a prompt). You need an environment that provides those objects.

Categories

Resources