JavaScript String Generator - Not Working (Sublime Text 3) - javascript

I am using Sublime Text 3 and whenever I build it with my build system for JavaScript. It gives me an error. Code below as well as error:
function makeid(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}
console.log(makeid(5));
And then the error:
[WinError 2] The system cannot find the file specified
[cmd: ['/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc', 'C:\\Users\\me\\Documents\\Projects\\Password Generator\\script.js']]
[dir: C:\Users\me\Documents\Projects\Password Generator]
[path: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\National Instruments\Shared\OpenVINO\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Users\me\AppData\Local\Microsoft\WindowsApps]
[Finished]
I tried running the code and it didn't work and I'm expecting it to generate me a random string.

Your "build system for JavaScript" expects you to have a /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc binary - that's an obviously macOS path, and you're evidently running on Windows.
You'll want e.g. node.js if you want to run console JavaScript on Windows, and then fix your build system to use node instead.

To generate a JavaScript string in Sublime Text editor, you can follow these steps:
Open Sublime Text editor and create a new file by selecting "File" > "New File" from the menu or by pressing "Ctrl+N" on Windows or "Cmd+N" on Mac.
Type the following code to create a string variable and assign a value to it:
var myString = "Hello, world!";
Save the file by selecting "File" > "Save" from the menu or by pressing "Ctrl+S" on Windows or "Cmd+S" on Mac.
Choose a location and name for the file and save it with a .js extension, for example "myFile.js".
To test the code, you can open a new browser window and create a script tag to reference the file,
Finally, open the HTML file in a web browser and check the console output to see the string value printed:

Related

Sublime Text Ctrl + B wont show output (JavaScript)

Here is my code:
var message = "Hello World";
console.log(message);
Here is the error after Ctrl + B:
/home/kazak/.config/sublime-text-3/Packages/User/javaScr.js: line 1: var: command not found
/home/kazak/.config/sublime-text-3/Packages/User/javaScr.js: line 2: syntax error near unexpected token `message'
/home/kazak/.config/sublime-text-3/Packages/User/javaScr.js: line 2: `console.log(message);'
[Finished in 0.0s with exit code 2]
[cmd: ['/bin/bash', '/home/kazak/.config/sublime-text-3/Packages/User/javaScr.js']]
[dir: /home/kazak/.config/sublime-text-3/Packages/User]
[path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
First make sure you have installed python and node.
Open sublime text > Tools > Build System > New Build System > copy and paste Python Build System code, change "cmd" path with your python location > press ctrl+s save the build file in default location with whatever file name you want but make sure the file extension is .sublime-build.
Do the same thing for javascript build system and change "cmd" path to your node location.
Python Build System Code
{
"cmd": ["/usr/path/to/your/python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
// if you want to see the execution information set "quiet":false
"quiet": true,
"selector": "source.python"
}
JavaScript Build System Code
{
"cmd": ["/usr/path/to/your/node", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true,
"selector": "source.js"
}
After you created two build system, now again open sublime text > Tools > Build System > Automatic
Open your javascript or python file press ctrl+b select your build system, you're ready to rock!

How do I choose JavaScript for my AppleScript SCPT file?

I'm calling an Applescript scpt file and when I opened the AppleScript editor it had an option to use JavaScript.
I would like to convert my AppleScript to JavaScript but can't find any documentation on it (announcements and such and redirects on apple).
Here is my AppleScript:
#!/usr/bin/osascript
on run argv
set output to "{\"1st Parameter\":\"" & first item of argv & "\"}"
return output
end run
More context:
I'm trying to loop through a directory and export from Excel. I only need to know about how to run JavaScript in a SCPT file but this is the background.
#!/usr/bin/osascript
on run argv
#goal is to export multiple files to csv
#the plan is to
#pass in folder and loop through files or
#pass in array of files (paths as a comma separated string)
#pass in single file and call script multiple times
set processReportsScript to "excel -e '" & first item of argv & "' '" -o '" & second item of argv & "'.csv'"
do shell script processReportsScript
end run
UPDATE:
While in Script Editor I'm able to run this JavaScript:
function run(args) {
var x = false;
var y = Application("Mail");
var running = y.running();
var id = y.id();
debugger;
if (x) {
console.log("Why isn't this being called?")
}
return "hello";
}
Based in part on this guide.
However when I save the JavaScript into the SCPT file and call it from an external application it gives the following error:
script error: Expected end of line, etc. but found “(”. (-2741)
It does not give any errors when using AppleScript.
FYI the external application is passing the script to osascript.
UPDATE 2:
I changed the extension from scpt to js and now it's running. I read that it's possible to pass in the language type using -l but when I do I get numerous variations of the error:
no such component " 'JavaScript'"
no such component " JavaScript"
As long as it works by changing the extension I think this works.
Both AppleScript and JavaScript for Automation (JXA) use the same file extension: ".scpt". When you are in the Script Editor, there is a language popup where you can select either:
The is no tool for auto-conversion from AppleScript to JXA.
For more info about JXA, see
JXA Resources

How to check whether chrome browser is installed or not using java script?

My requirement is I need to check whether Chrome browser is insatlled on the client machine or not using Javascript. I have searched on the net not able to find the way out.
Please help in getting this done.
You can't do that with JavaScript, and even if you could, you shouldn't.
JavaScript on the client doesn't have access to the user's system, for very good reasons. (Think, servers with bad intentions.)
You can check if the browser is Chrome with the next code
if(!window.chrome){
//Chrome code
}else{
// Chrome block
}
You can't. Not with JavaScript. However, you can check whether the browser that is currently being used to view your webpage is Google Chrome or not.
<script type="text/javascript">
if(window.chrome){
document.write("Browser is Chrome");
}
else{
document.write("Please download Chrome");
}
</script>
You can't get that kind of information directly from javascript.
What you can do is use that PowerShell command in a script and save the result in a file that you'll read later using javascript.
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation, Publisher, InstallDate | Format-Table -AutoSize
This will get you all the installed programs on the machine from the HKEY_LOCAL_MACHINE registry folder.
The exact path to the folder from wich the informations are retrieved is : HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\
The given command will display you the application name followed by it's version, it's install location, publisher name and installation date in a PowerShell terminal.
If you want to output that list in a file simply add >FileName.txt after the command before pressing enter.
Note that by default the file will be created in the C:\Users\YourUserName\ folder so if you want the file to be created in a specific location you'll have to use the CD command to get to that specific location before executing the Get-Item-Property command.
This will get you done for the get installed programs on a machine part.
Now we can get into the check if app x is installed on the machine part.
First load the previously generated file in your js application you will use it's content to determine if an application is installed on the computer.
The faster way to get if 'chrome' is installed will be to load the file as a string and then do that basic stuff :
if (string.includes('chrome') == true) {
// chrome is installed on the machine
// you can do some more stuff
// like extracting it's path from the file content
} else {
console.log('error: chrome is not installed on this computer');
}
Needless to say that this will only work if used on the same computer from which you want to check the installed applications.
Edit: If you want a more practical file to use in javascript you can replace
Format-Table -AutoSize >FileName.txt
with :
Export-Csv -path .\FileName.txt -NoTypeInformation
this way you can split your file lines using the string.split(',') method and don't have to do some extra stuff to deal with the spaces between data.
Edit 2:
Here's a full working implementation that will let you retrieve informations from a PowerShell script directly from your javascript using NodeJs.
get_programs.ps1 (PowerShell script file) :
chcp 65001 # sets the encoding for displaying chars correctly
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation | ConvertTo-Csv -NoTypeInformation
chcp 850 # restores the default encoding set this will avoid police changes due to the terminal modifications
Notice the change at the end of the command which is now:
| ConvertTo-Csv -NoTypeInformation
this allows to log data in the PowerShell terminal in the csv format which will simplify it's parsing as a string.
If you don't want to use another file to hold those few PowerShell
commands you can use this
child = spawn("powershell.exe",[`chcp 65001
Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, DisplayVersion, InstallLocation | ConvertTo-Csv -NoTypeInformation
chcp 850`]);
as a replacement for
child = spawn("powershell.exe",["./get_programs.ps1"]);
If you choose to do this don't forget to escape the \ chars else it will not work.
app.js :
var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",["./get_programs.ps1"]); // here we start our PowerShell script "./" means that it's in the same directory as the .js file
let chromeDetails;
child.stdout.on("data", (data) => { // data event
// here we receive each outputed line in the PowerShell terminal as an Uint8Array
if (data.includes('Chrome')) { // check for the 'Chrome' string in data
chromeDetails = data.toString(); // adds data converted as string
}
});
child.stderr.on("data", (data) => { // logs errors
console.log(`Powershell Errors: ${data}`);
});
child.on("exit", () => { // exit event
console.log("Powershell Script finished");
if (chromeDetails != undefined) {
console.log(`> chrome has been detected on this computer
available informations (appName, version, installPath):
${chromeDetails}`);
} else
console.log('> chrome has not been detected on this computer');
});
child.stdin.end(); // we end the child
Expected output :
Powershell Script finished
> chrome has been detected on this computer
    available informations (appName, version, installPath):
    "Google Chrome","103.0.5060.114","C:\Program Files\Google\Chrome\Application"
If you are not on Windows you may want to take a look at Spawning .bat and .cmd files on Windows from the NodeJs documentation to get hints on how to adapt the above app.js code to work on your system.

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.

Filesystem operations through Thunderbird Extension

I would like to do some operation on my filesystem through a Thunderbird plugin.
For example create a folder at a specific location and a text file,
containing some data from thunderbird, in this folder.
As you know, Mozilla Extensions consist of javascript code.
So I looked for this, found some code about ActiveXObject, which is not working for Thunderbird.
Any ideas what should I do about it?
First, read up on extensions in general (Firefox docs apply to Thunderbird as well, except for the Add-on SDK, which does not really work with Thunderbird; go the XUL overlay route).
Then there are multiple ways to perform File I/O, in particular XPCOM stuff and OS.File:
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O
https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread
Here is a code snippet from my extension. I create text file in Profile directory and then I add some text into this file.
var path = Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path + "\\";
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(path);
file.append("settings.txt")
file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0664)
var outputStream = Components.classes["#mozilla.org/network/file-output-stream;1"].createInstance( Components.interfaces.nsIFileOutputStream );
outputStream.init( file, 0x04 | 0x10, 0664, 0 );
var output = "some text here"
var result = outputStream.write( output, output.length );
outputStream.close();

Categories

Resources