Distinguish between different linux distros in nodejs - javascript

Basically I want to be able to run different code depending on what os you have.
I've found out that the os.platform() function will return "win32", "win64", "darwin", or "linux" (possibly others?), but I can't seem to get any more specific information.
Ideally I want to be able to tell if Gnome, Unity, KDE, or some other desktop environment is being used.

Getting the active desktop environment/window manager is not a node-specific problem. There are different approaches (some better than others) that include using pgrep to check running process names against known DE/WM binary names and using other tools such as HardInfo or wmctrl.

What I ended up using was a bash scripts from mscottnielsen. It seems to use the best of many different commands to find out what desktop environment is being used. Unfortunetally, it's kind of hard to figure out the exact string that gets outputed by it (It doesn't say anywhere what strings get outputed), but other then that it does the job.
See the script here.

Related

Using JavaScript in a NodeJS environment, can you find a window handle value of a running application?

I'm writing some tests for my React-Native application (using JS) in a NodeJS environment. In one scenario, I need to attach to an already-running Windows application. In order to attach to this Application, I need to know the NativeWindowHandle value.
For example, if you open Inspect.exe on a window, you'll find the "NativeWindowHandle" hex value.
Is there anyway I can find this value programmatically?
What I've Tried:
I'm able to find the PID of the app using:
const exec = require('child_process').exec;
exec('tasklist', function (err, stdout) {
....
}}
However, I haven't been able to turn that into the window handle. Does anyone have any ideas here? Is this possible?
This can be reliably accomplished by writing a native (C++) node addon which calls the appropriate Windows API functions and passes the results back to JS land.
eg you might want to call FindWindowEx and Windows will find and return the HWND (native window handle) of the matching open window. Or use one of the enumeration functions if you need to do the search yourself.
I did a quick search of npm and it looks like there might be a few packages that have done this work already, but you'll need to evaluate them.
If none of the npm packages will work, you'll need to write it yourself. This isn't too hard if you have a little C++ knowledge, but alternatively you might be able to get away with using node-ffi, which lets you write everything in JS and marshals the native calls for you.
(Using ffi will be a little slower than writing the native module yourself, but for your purposes that doesn't really matter. Either native or ffi will be much faster than spawning child processes.)

How to get the current foreground application in electron(Javascript)

How can I detect if, for example, a browser is currently open?
I need this in my electron-application.
ty :)
I've found nothing like this online.
I've only found how I can check which window is open from the windows I have in my own application, but I need to know, what else is opened.
It should be something like this:
if(Application.isOpen('Google Chrome'){}
Unless someone has built a specific electron api to do this (which I can't find), then from electron...no. However, the beauty of electron being built with node.js, means that any node module should be able to do the job for you.
For example, ps-list should be able to get you all currently running processes.
psList().then(processes => {
console.log(processes)
})
Which gives a list for me, including:
Just be aware that you need node access from the electron thread attempting to use this lib.
This can easily be abstracted to do a name search in the list for you to get your desired functionality.
You can use find-process in case you need to search by given name, name pattern or pid.

Run local JavaScript functions from Python 3

So, I'm teaching myself various AI techniques, and I figured the best way to do so would be to create my own Python bot which can play the game Pokemon using an online open-source Pokemon simulator.
The issue is that this simulator has all its source code written in JavaScript, whereas my bot uses Python. At first, I solved the problem of grabbing the full list of valid Pokemon and such by simply downloading the server's .js files, which (handily) contained all valid Pokemon/moves as JSON objects that I could easily import into Python. This was all well and good when I just needed Pokemon names and such, but now that I'm building out the actual engine I've discovered that it uses these same JSON files for its actual gameplay code.
For example, here's the Pokemon "Ability" Aftermath. Pay attention to onAfterDamage:
"aftermath": {
desc: "If this Pokemon is knocked out with a contact move, that move's user loses 1/4 of its maximum HP, rounded down. If any active Pokemon has the Damp Ability, this effect is prevented.",
shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.",
id: "aftermath",
name: "Aftermath",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact'] && !target.hp) {
this.damage(source.maxhp / 4, source, target);
}
},
rating: 2.5,
num: 106,
}
As you can see, onAfterDamage is a JavaScript function, one that I can't easily call from Python (to my knowledge). So now I'm at a crossroads:
Stop grabbing the .js files from the server and write my own code entirely in Python, essentially "translating" the JavaScript code myself.
Rewrite my entire bot in JavaScript instead of Python, although I'm far less experienced and comfortable in JavaScript.
Find a way to run the JavaScript code I'm downloading from the server from within my Python bot, calling arbitrary functions from within the code and returning the results.
Option 1 has the issue of rapidly becoming out of date -- when new Pokemon mechanics are introduced or new Pokemon are created, I wouldn't get it "for free" -- I'd have to figure out what changed and implement the changes myself.
I'd like to avoid Option 2 just because I'm not very comfortable writing JavaScript -- it's something I've dabbled with in the past, but it's far from my favorite language and not something I want to deal with when it's not the primary focus of my project.
I realize that Option 3 is a pretty massive security risk -- while I'm reasonably sure that a man-in-the-middle attack won't happen to a bot that likely nobody will ever use but myself, I'm still just downloading random JavaScript from a server somewhere and trying to execute it.
I've seen things like PyExecJS, but they're no longer maintained, and I haven't really seen anyone recommending a good replacement for them. PyExecJS's functionality is exactly what I'm looking for (namely the function execjs.eval(js_code)), but I'm not sure I want to use something that's reached EOL. I've seen the answers here, but they don't recommend any replacements for PyExecJS; they only show that user that they're using it wrong.
I've also seen people suggest Selenium or running a headless browser, but I'm not sure if I want to deal with all that extra overhead. The very first programming project I ever did outside of school was very similar to this, and I wound up coding it in Java using Selenium. I wasn't happy with that experience, and I'm not looking forward to having to do it again, especially when I only need to execute JavaScript I already have downloaded locally.
Am I completely off-base here? Is there another approach I should take, or should I just get to work translating all this JS code to Python by hand?
Ideally you could run your .js-file from cli just like any other executable. With node -e you can execute your JavaScript code on cli.
Relating to this post https://stackoverflow.com/a/450329/6478277 you could similarly run your script with your local node.
node -e "function func(){console.log(123)};func();"
From a file
print subprocess.check_output(['node -e "require(\"./file.js\").test()"'])
Where file.js could be something like
module.exports = {
test: () => console.log(123),
}

SSH with Javascript without GUI

What I want to make is a Operating System based on Ubuntu which will use the web
I want to make the items clickable. If you click on an app-icon, the application will open. I tried to use WebSockets, but they are'nt that easy to use.
I tried PHP, with exec(), popen(), system() and I tried ssh2 functions. Doesn't work or too slow.
I can't use a GUI like shellinabox, because I only want to connect to localhost and run some commands like 'firefox' or 'sensible-browser' or like 'gedit'. That's why I want help.
I googled the whole day and found nothing. I'm searching for a simple solution. Just a connection and just some commands. No extra GUI, just that simple things!
Thanks,
Amanush.
-------------------------------------------[SECOND QUESTION (EDIT)]------------
I made my own protocol and it's working well!
One last question. My html:
<html>
<body>
Open firefox
</body>
</html>
My .desktop file:
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Terminal=false
Exec=/usr/bin/cloudjerun -c gedit
Name[en_US]=Gedit
Comment[en_US]=Small, easy-to-use program to access iTunesU media
Name=TunesViewer
Comment=Small, easy-to-use program to access iTunesU media
Icon=/usr/share/icons/hicolor/scalable/apps/tunesview.svg
Categories=Application;Network;
MimeType=x-scheme-handler/cloudje;
Comment[en_US.utf8]=Small, easy-to-use program to access iTunesU media
Tutorial: http://jarrpa.net/2011/10/28/creating-custom-url-handlers-in-ubuntu-11-04-11-10-gnome-3-0/
Ok, it's always executing gedit. The reason is the line Exec=/usr/bin/cloudjerun -c gedit.
That's cool, but I want to run firefox as well, with 'cloudje:firefox' in the HTML-file. How can I replace -'-c gedit' with '-c firefox', '-c skype' or '-c sensible-browser', automaticly?
I suggest you register a custom protocol handler for your OS on the machine.
ie.: mysweetos://launchapp/chromium
you can find info about this with a quick google of "registering a custom protocol handler linux"
You would have to write some software/script on the linux machine to receive this request and execute the required application.
This looks very similar, and could be a significant part of what you are trying to accomplish. Technical details here, looks like it requires GTK3.2+

How would I solve a coding puzzle with Javascript?

There is a website called Gild.com that has different coding puzzles/challenges for users to do. They can be completed in wide array of languages including Javascript. I am interested in solving these puzzles in Javascript, but I am unsure of the following:
How am I supposed to access the input file which is supposed to be passed as an argument?
How am I supposed to output the result?
My understanding of Javascript is that it is run from within an HTML page and that output really is only in the form of placing values in the HTML, modifying the DOM, etc. For that reason it is not clear to me how Javascript can be used for solving these types of problems. Can someone who has used Gild before or has some insights into my question suggest how to proceed?
An example of a problem would be: the given input file contains a positive integer, find the sum of all prime numbers smaller than that integer and output it.
EDIT: Some of the solutions below involve using external resources, but on Gild, I am supposed to put my solution in their editor and then submit it that way, like the following picture shows:
In other words, I don't think my solution can have access to Node.js or other external resources.
Edit: Here are some interesting articles that I have found that I think are the answer to my question:
http://www.phpied.com/installing-rhino-on-mac/
http://www.phpied.com/javascript-shell-scripting/
I haven't spent much time on Gild, but I do a lot of similar types of problems on Project Euler. I think the best way to go is probably Node.js.
If you're not familiar, Node is basically server-side JavaScript that runs in Google's V8 engine. Installing it on your own Mac/Windows machine takes about 2 minutes. It's also really fast (considering it's JavaScript).
And you'd use it like this:
var fs = require('fs'); // the filesystem module
var contents = fs.readFileSync('theFile.txt', 'utf-8');
// Do stuff with the file contents...
Everything after those first two lines can be done with the same JS you'd write in the browser, right down to calling console.log() to spit out the answer.
So, if you wrote your script in a file on your desktop called getprimes.js, you'd open up your terminal and enter node ~/Desktop/getprimes.js (assuming you're on a Mac)
If you're:
on a Mac,
planning to do a lot of these puzzles, and
willing to pay $10, then
I highly recommend CodeRunner. It encapsulates runtimes for a variety of languages — from C to JavaScript — and lets you quickly build and run any sort of one-off code. Just hack together your code, ⌘R, and the results are printed right there in the same window.
I haven't used any file-based JavaScript in CodeRunner, but I imagine kennis's suggestions would apply. To output your results:
console.log(...)
Easy as pie!

Categories