Make an AppJS project into a single exe - javascript

I have been reading online for days and I am unable to find a solution for this that I can get working.
I would like a single exe file that unpacks to temporary location when you run the file which can be shared and sent to people. Ideally I would like to hide my JavaScript files.
I just need 1 file that can be sent easily.
-Fasani

i don't know of any simple way to do this
but i had a similar problem a while ago and i created a VB.Net program to do this for me
First download portable 32bit version of node here : Node.exe
if you have visual studio installed create a new project then from the solution explorer go to your projects properties and add node.exe and your .js file as Resources.
then in the formload (if you don't want your program to have a ui) or in a buttons click event place these code:
Try
Dim tmpp = System.IO.Path.GetTempPath & "NodeTmp"
If (Not System.IO.Directory.Exists(tmpp)) Then System.IO.Directory.CreateDirectory(tmpp)
If Not System.IO.File.Exists(tmpp & "\tmp_node.exe") Then _
My.Computer.FileSystem.WriteAllBytes(tmpp & "\node.exe", My.Resources.node, False)
System.IO.File.WriteAllText(tmpp & "\jsfile.js", My.Resources.jsfile)
System.IO.File.WriteAllText(tmpp & "\batfile.bat", """" & tmpp & "\tmp_node.exe"" """ & tmpp & "\jsfile.js""")
Dim p As New Process()
p.StartInfo.FileName = "cmd.exe"
p.StartInfo.Arguments = "/C """ & tmpp & "\pz.bat"""
p.StartInfo.CreateNoWindow = True
p.StartInfo.UseShellExecute = False
p.Start()
'Timer1.start()
Catch ex As Exception
MsgBox("Error")
End Try
the above code creates a folder called NodeTmp in the C:\user{name}\appdata\local\Temp and extracts node.exe (from a file resorce called "node") in that folder then extracts jsfile.js (from a file resource called "jsfile") in the same folder then creates a .bat file and runs it
to Delete .js file after it is run (it is created and deleted in less then 1sec so it is kind of hidden from user):
create a timer called Timer1 and set its interval to something like 150ms and uncomment the line Timer1.start() from above code and put the following sub somewhere in code
Sub pz_cleanup() Handles Timer1.tick
Try
Dim tmpp = System.IO.Path.GetTempPath & "PZT"
System.IO.File.Delete(tmpp & "\pz.bat")
System.IO.File.Delete(tmpp & "\pz.js")
Timer1.stop()
Catch ex As Exception
End Try
End Sub
This is definitely not the best way to do this , but it worked for me , the only downside it had for me so far was its need for .net framework to be installed on other users computer which not all of them had it
if you want a cmd to open and show nodes output comment the line that sets CreateNoWindow to true
----- not part of answer but if you want to have a UI and put a close button there to so users don't have to end task node from taskmanager use this code:
Try
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("tmp_node")
For Each p As Process In pProcess
p.Kill()
p.WaitForExit()
Next
Catch ex As Exception
MsgBox("Error")
Return True
End Try
hope this helps , you can do similar thing in other languages too if you are more comfortable with them then VB.Net

Related

JS script is not cleaning the spool folder

I'm having a task where different users have access to written by an external supplier (computer with limited access) the Kiosk app, and Windows 10 is running under the hood. A kiosk gives access to my company's local web-based apps via browser. Users can print for i.e. working schedules, Holiday requests, payslips etc. Due to GDPR and various other security concerns, I need to ensure that all printing jobs on this particular machine are clean when the user closes the internet browser.
I wrote the simple script in JS that I can add to the main Kiosk. The app will then run the script when the user closes it, and the browser logs off the computer.
The script supposed to run & clean a printer folders which in my case are:
C:\Windows\Sysnative\spool\PRINTERS\*
C:\ProgramData\SPS\Jobs\*", true);
However, my tests indicate that the script somehow does not work!
In one of my Test-Scenarios: Employee A is printing a pay slip, that printing Q is not cleared and now Employee B will log in to the computer and can still print something that does not belong to him.
Here is my code, if you have any idea why printing Q is not cleared, or have maybe a better idea regarding .js code
SiteKiosk.OnReset = waitBeforeDelete;
function waitBeforeDelete()
{
//Give SiteKiosk some time to run through its default session end/screensaver activation methods
evtid = SiteKiosk.Scheduler.AddDelayedEvent(3000, deleteFolders);
}
function deleteFolders(eventID)
{
try
{
//Deleting the folders with the help of the FileSystemObject
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.DeleteFile("C:\\Windows\\Sysnative\\spool\\PRINTERS\\*", true);
fso.DeleteFile("C:\\ProgramData\\SPS\\Jobs\\*", true);
SiteKiosk.Logfile.Notification("---------------------------------Deleting folder content was successful---------------------------------");
}
catch (e)
{
//Create a SiteKiosk logfile entry in case something goes wrong
SiteKiosk.Logfile.Notification("---------------------------------There was an error deleting the folder content: " + e.description + "---------------------------------");
}
}

How can an image be saved with JavaScript for Automator (JXA) in macOS Preview application?

There is an image open in the Preview application, and it is unsaved.
I have tried this code, by building and running a standalone script in Script Editor:
var preview = Application('Preview')
var preview.documents[0].close({ saving: true, savingIn: '/Volumes/USB Drive/Untitled-Image.png' })
I see this in the logs
app = Application("Preview")
app.documents.at(0).Symbol.toPrimitive()
--> Error -1700: Can't convert types.
app.documents.at(0).Symbol.toPrimitive()
--> Error -1700: Can't convert types.
However, I'm not sure I'm reading the docs correctly, and I'm not sure how to further debug this code. A satisfactory alternative here would be to send a keystroke to save and click the Save button.
What can I do to persist the image in Preview to a file?
One can declare paths speculatively in JavaScript using Path('...'), and then use the save command to save the image to the file that will be created at that path:
Preview = Application('com.apple.Preview');
ImageFilepath = Path('/Users/CK/Pictures/Preview_SavedImage.jpg');
Preview.documents[0].save({ in: ImageFilepath });
This code worked for me.
var preview = Application('Preview')
var photo = preview.documents[0]
photo.close({ saving: 'yes', savingIn: Path("/Path/To Some/file_name.png") })
Upon execution, in the Replies log of Script Editor window, something slightly different from the question sample is logged.
app = Application("Preview")
app.close(app.documents.at(0), {savingIn:Path("/Path/To Some/file_name.png"), saving:"yes"})
I was able to figure this out by studying the scripting dictionary for macOS Mojave 10.14 as well as the Release Notes for JXA; there is a similar example under Passing Event Modifiers section of that.
From the Script Editor scripting dictionaries, this is the entry for the close method in the Standard Suite:
close method : Close a document.
close specifier : the document(s) or window(s) to close.
[saving: "yes"/‌"no"/‌"ask"] : Should changes be saved before closing?
[savingIn: File] : The file in which to save the document, if so.
Note the key differences between the working code here and the code in the question:
Specify a Path object when passing the savingIn option to close.
Specify a the saving option as one of "yes", "no", or "ask" (not true).
If you're new to JXA, Automator, and/or Script Editor for Mac, checkout the JXA Cookbook.
If this answer helps you, you're probably having a bad time, so best of luck!

Automating a routine procedure in Windows 10 (Mostly interacting with the browser)

I'm trying to figure out if I can automate the following tasks,
Open the IE
Navigate to a site
Enter login and password
From the user page - Search XXX
Right click on the returned result
From the drop down menu Left click save
Save to a designated folder
I need to repeat this task for 500 times, what's the best way to go about it? I'm thinking of creating a VB Script but not sure if I can do all above with it..
I also found that this can be done in javascript as well? but I don't even know where to start from.
Can someone please give me the right direction? thanks,
1) Yes, you can do it with the Windows Script Host using VBScript or JScript (doesn't matter), using the InternetExplorer.Application COM object.
For details, check this thread: Vbscript for automated website login testing
See also the MSDN documentation about the IE object model: https://msdn.microsoft.com/en-us/library/ms970456.aspx
VBScript example by Francis MacDonald copied from the other thread:
Dim IE
Dim Helem
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = 1
IE.navigate "http://www.example.com"
Set Helem = IE.document.getElementByID("formUsername")
Helem.Value = "username" ' change this to yours
Set Helem = IE.document.getElementByID("formPassword")
Helem.Value = "password" ' change this to yours
Set Helem = IE.document.Forms(0)
Helem.Submit
Do While (IE.Busy)
WScript.Sleep 10
Loop
Dim someElement
Set someElement = IE.document.getElementByID("someElement")
If Len(someElement.innerText) > 0 Then
MsgBox "logged in"
End If
2) There is a tool designed specifically for this task which may help you further: Selenium.

Read files from SD Card with mosync/phonegap on Android with pure Javascript

I know this question was asked many times before but I cannot figure it out anyhow.
I'm able to write a text file to a directory on the sdcard (android 4), but no way to read it back again, using this code:
function get_file () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, getFilesystem, fail);
}
function getFilesystem(fs) {
alert("getFilesystem -> backup.txt"); // OK !
// alert("filesystem.name: "+fileSystem.name); // = persistent
// alert("filesystem.root.name: "+fileSystem.root.name); // = long number
//
fs.root.getFile("../../../../../../sdcard/test/backup.txt", {create: false, exclusive: false},
function(fileEntry) {
alert(fileEntry.fullPath); // shows that my path is appended to "data/.."
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert(+evt.target.result); // NOT SHOWING !
};
reader.readAsText(file);
}, fail);
}, fail);
}
I wrote the file using the writer function into the directory sdcard/test using this sequence of ../ - this is an ugly code but working !
But fs.root.getFile does not work in the same way - the fullPath information it returns shows that my path given is APPENDED to "/data/data/com.appname/files" but does not replace it !
The onloadend function obviously isn't working since i never got the alert message, neither did I get an error message.
Change of path to "file:///sdcard/test" or "sdcard/test" has no effect either.
Any help is highly appreciated - thank you in advance !
Chris
Please refer PHONEGAP DOCUMENT
From this you will get working example of getting file from sdcard.
And if you have problem in downloading a file please refer LINK
I think in Place of "/sdcard/backup.txt" try to use only "backup.txt".
It seems to work fine.
PhoneGap takes care of the details of the path ,also works with directories.
So finally I could figure it out:
To access the directory (on Android 4.0, Samsung Note 8) I had to go up literally all directories from /data/data/com.app-name/files/apps/(random no.)/ back to the sdcard by choosing:
fs.root.getFile("../../../../../../sdcard/test/backup.txt", ...
in mosync Reload client.
"Compiling" the app with mosync apk would require only 4 times "../" because the file hierarchy there is lower than in the Reload Client. In any case have to check in file explorer (root access required).
Different from that is when you compile in the cloud with phonegap - then indeed the root path is sdcard ! You then cannot go to the data directory as far as I could find out.
This path works with write and read in mosync - my mistake was that I had line break character "\n" inside the text file. In this case I could write it, but the reader stops without error message.
Hope that will help someone else as well !
Chris

PhantomJS using too many threads

I wrote a PhantomJS app to crawl over a site I built and check for a JavaScript file to be included. The JavaScript is similar to Google where some inline code loads in another JS file. The app looks for that other JS file which is why I used Phantom.
What's the expected result?
The console output should read through a ton of URLs and then tell if the script is loaded or not.
What's really happening?
The console output will read as expected for about 50 requests and then just start spitting out this error:
2013-02-21T10:01:23 [FATAL] QEventDispatcherUNIXPrivate(): Can not continue without a thread pipe
QEventDispatcherUNIXPrivate(): Unable to create thread pipe: Too many open files
This is the block of code that opens a page and searches for the script include:
page.open(url, function (status) {
console.log(YELLOW, url, status, CLEAR);
var found = page.evaluate(function () {
if (document.querySelectorAll("script[src='***']").length) {
return true;
} else { return false; }
});
if (found) {
console.log(GREEN, 'JavaScript found on', url, CLEAR);
} else {
console.log(RED, 'JavaScript not found on', url, CLEAR);
}
self.crawledURLs[url] = true;
self.crawlURLs(self.getAllLinks(page), depth-1);
});
The crawledURLs object is just an object of urls that I've already crawled. The crawlURLs function just goes through the links from the getAllLinks function and calls the open function on all links that have the base domain of the domain that the crawler started on.
Edit
I modified the last block of the code to be as follows, but still have the same issue. I have added page.close() to the file.
if (!found) {
console.log(RED, 'JavaScript not found on', url, CLEAR);
}
self.crawledURLs[url] = true;
var links = self.getAllLinks(page);
page.close();
self.crawlURLs(links, depth-1);
From the documentation:
Due to some technical limitations, the web page object might not be completely garbage collected. This is often encountered when the same object is used over and over again.
The solution is to explicitly call close() of the web page object (i.e. page in many cases) at the right time.
Some included examples, such as follow.js, demonstrate multiple page objects with explicit close.
Open Files Limit.
Even with closing files properly, you might still run into this error.
After scouring the internets I discovered that you need to increase your limit of the number of files a single process is allowed to have open. In my case, I was generating PDFs with hundreds to thousands of pages.
There are different ways to adjust this setting based on the system you are running but here is what worked for me on an Ubuntu server:
Add the following to the end of /etc/security/limits.conf:
# Sets the open file maximum here.
# Generating large PDFs hits the default ceiling (1024) quickly.
* hard nofile 65535
* soft nofile 65535
root hard nofile 65535 # Need these two lines because the wildcards (above)
root soft nofile 65535 # are not applied to the root user as well.
A good reference for the ulimit command can be found here.
I hope that puts some people on the right track.
I had this error come up while running multiple threads in my ruby program.
I was running phantomjs with Capybara-poltergeist and each thread was visiting a page opening up the same CSV file and writing to it.
I was able to fix it by using the Mutex class.
lock = Mutex.new
lock.synchronize do
CSV.open("reservations.csv", "w") do |file|
file << ["Status","Name","Res-Code","LS-Num","Check-in","Check-out","Talk-URL"]
$status.length.times do |i|
file << [$status[i],$guest_name[i],$reservation_code[i],$listing_number[i],$check_in[i],$check_out[i], $talk_url[i]]
end
end
puts "#{user.email} PAGE NUMBER ##{p+1} WRITTEN TO CSV"
end
end

Categories