Call VBScript from Node.js - javascript

To answer a request from the client, Node.js needs to export charts from Excel files in images into a repository.
I chose to use a VBA Macro because I don't think I have other solutions.
The VBA code is working properly (when I call it manually) but I wish I could connect it with Node.js events.
VBScript allows me to call a VBA Macro in my script.vbs file :
Option Explicit
On Error Resume Next
CallVBA
Sub CallVBA()
Dim ApplicationExcel
Dim ClasseurExcel
Set ApplicationExcel = CreateObject("Excel.Application")
Set ClasseurExcel = ApplicationExcel.Workbooks.Open("H:/macrosVBA.xlsm")
ApplicationExcel.Visible = False
ApplicationExcel.Run "ChartUpload"
ApplicationExcel.Quit
Set ClasseurExcel = Nothing
Set ApplicationExcel = Nothing
End Sub
My problem now is to run the VBScript in the JavaScript file :
var objShell = new ActiveXObject("WScript.shell");
objShell.run('H:/script.vbs');
I get the error :
ReferenceError: ActiveXObject is not defined
Adding win32ole and winax doesn't change anything, they don't seem to work anymore.
I'm looking for your help to have another solution or to fix my error with ActiveXObject.
Thanks in advance

Your Node.js is probably 64bit, whilst your Office/Excel is probably the 32bit version.
You need to run the 32bit VBScript interpreter in order to access the 32bit CreateObject("Excel.Application")
const { spawn } = require("child_process");
const bat = spawn("C:\\Windows\\SysWOW64\\wscript.exe", ["H:\\script.vbs"]);

Related

How to read and write to a file (Javascript) in ui automation?

I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.

How to fetch file content (basically read) a local file in javascript for UIAutomation iOS

Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).

Getting the current user name or computer name in Extendscript

I'm finally getting some headway made in my script for InDesign CS6. Now, in order for it to know to which printer it should print a document, I need to query which computer the script is running on. Barring that, perhaps the name of the currently logged-in user, which is really the same thing. This is a Mac OS X environment, by the way. Can anyone help or at least point me in the right direction?
As seen on http://jongware.mit.edu/idcs6js/pc_$.html, the $.getenv() method can be used to get any environment variable. On Windows you could use $.getenv("COMPUTERNAME"), and on Mac $.getenv("HOSTNAME") should work.
Let me know if this doesn't work. I don't have a Mac to test on, but there's probably other options.
EDIT 1: Are you using InDesign Server? If so, app.serverHostName and app.serverSettings.hostName would work.
EDIT 2: Here's another possible solution:
var outputFile = new File(Folder.desktop.fsName + "/GetHostName.sh");
outputFile.open("w");
try {
outputFile.write("scutil --get HostName > ~/Desktop/HostName.txt");
}
finally {
outputFile.close();
}
outputFile.execute();
var inputFile = new File(Folder.desktop.fsName + "/HostName.txt");
inputFile.open("r");
try {
var hostName = inputFile.read();
}
finally {
inputFile.close();
}
$.writeln("Host Name: " + hostName);
The idea is to write a shell script to file and then execute it. The shell script gets the host name and writes it to a file. Then we open the file and read the host name.

how to refer SQLite SIMPLE way in Javascript-App just use 'DB_open, execute SQL..' VS2012

I want to write an App (JS) with SQLite (VS2012). So I can't find a easy beginnerguide for this. When I install the SQLite for Windows Runtime. There is a C++ code (GitHub) to insert in the Projekt.
So, what happens with the JS - Projekt?
How can JS refer to properties and methodes of the DB-Objekt (dll, ocx, whatever from the SQLite-Runtime) just to open DB, execute SQL etc. in a simple way?
In Android-Browser following simple JS code (no more) is korrekt:
var shortName = 'testDb';
var version = '1.0';
var displayName = 'test db';
var maxSize = 1048576; // in bytes
mydb = window.openDatabase(shortName, version, displayName, maxSize);
function(transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS person(id INTEGER ..);', [], NullDataHandler, errorHandler);
}
Is somebody here - can show me the same SIMPLE in VS2012 without an Overhead, advanced settings and error-mangement - I can't follow the code?
1. DB_open : ..
2. Execute SQL : ..
Many Greetings from Bavaria
ralphi
PS: Why isn't it allowed to insert links?
I assume your Javascript is running on a web page. Actually, There is no way to manipulate the Sqlite database from a web page. For security reason, the ability to access local files from a web page is strictly limited. Despite new HTML5-supported browsers allow you to access local files in a limited and safe way, directly using local database is not possible in HTML world.

WIX: Where and how should my CustomAction create and read a temporary file?

I have a script CustomAction (Yes, I know all about the opinions that say don't use script CustomActions. I have a different opinion.)
I'd like to run a command, and capture the output. I can do this using the WScript.Shell COM object, then invoking shell.Exec(). But, this flashes a visible console window for the executed command.
To avoid that, I understand I can use the shell.Run() call, and specify "hidden" for the window appearance. But .Run() doesn't give me access to the StdOut of the executed process, so that means I'd need to create a temporary file and redirect the exe output to the temp file, then later read that temp file in script.
Some questions:
is this gonna work?
How do I generate a name for the temporary file? In .NET I could use a static method in the System.IO namespace, but I am using script here. I need to insure that the use has RW access, and also that no anti-virus program is going to puke on this.
Better ideas? I am trying very hard to avoid C/C++.
I could avoid all this if there were a way to query websites in IIS7 from script, without resorting to the IIS6 Compatibility pack, without using .NET (Microsoft.Web.Administration.ServerManager), and without execing a process (appcmd list sites).
I already asked a separate question on that topic; any suggestions on that would also be appreciated.
Answering my own question...
yes, this is going to work.
Use the Scripting.FileSystemObject thing within Javascript. There's a GetTempName() method that produces a file name suitable for temporary use, and a GetSpecialFolder() method that gets the location of the temp folder. There's even a BuildPath() method to combine them.
so far I don't have any better ideas.
Here's the code I used:
function GetWebSites_IIS7_B()
{
var ParseOneLine = function(oneLine) {
...regex parsing of output...
};
LogMessage("GetWebSites_IIS7_B() ENTER");
var shell = new ActiveXObject("WScript.Shell");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var tmpdir = fso.GetSpecialFolder(SpecialFolders.TemporaryFolder);
var tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName());
var windir = fso.GetSpecialFolder(SpecialFolders.WindowsFolder);
var appcmd = fso.BuildPath(windir,"system32\\inetsrv\\appcmd.exe") + " list sites";
// use cmd.exe to redirect the output
var rc = shell.Run("%comspec% /c " + appcmd + "> " + tmpFileName, WindowStyle.Hidden, true);
// WindowStyle.Hidden == 0
var ts = fso.OpenTextFile(tmpFileName, OpenMode.ForReading);
var sites = [];
// Read from the file and parse the results.
while (!ts.AtEndOfStream) {
var oneLine = ts.ReadLine();
var line = ParseOneLine(oneLine);
LogMessage(" site: " + line.name);
sites.push(line);
}
ts.Close();
fso.DeleteFile(tmpFileName);
return sites;
}

Categories

Resources