Ok, so I'm creating a webpage using socket.io in node.js.
This works great, and data is going to each device as it should.
Now i want to expand, and use node.js to control my pc.
I've read this: Child Process
and gotten to this code wich runs an executable, and prints its output in the console.
var spawn = require('child_process').spawn;
var ahk = spawn('outsideNode.exe');
ahk.stdout.on('data', function(data){
console.log(data.toString());
});
Here is the code, or script for outsideNode.exe that gets launched.
I'm using AutoHotKey for this.
Loop,10
{
FileAppend,External program spawned by Node.js says hi!,*
Sleep,1000
}
ExitApp
This works one way. Node.js captures AHK's output. Now, the problem i'm having is, how do i SEND data from node.js? And how do i recieve it in AHK?
I do belive i need to read about stdio. But i'm new to the std's.
My current solution is using Node.js to write a .txt file to disk with the command i want to give, and a seperate .exe file that reads the .txt and executes the command and exits. This works, but it is slow-ish, and just feels wrong to do it this way.
Also, I want it to be asynchronous, or synchronous? The one where i can do other stuff with node.js while the executable does its thing. Now i have to wait to be sure the file can be overwritten.
Any input on how to this is greatly appreciated.
There is the option to pass arguments to the spawned app. Maybe that's already what you are looking for. How to handle the arguments in your exe is another question related to some other programming languages. In node, child processes run asynchronous and non-blocking, that's the one you are looking for.
However, if you want to communicate between the programs, you can write to the stdin of the childprocess like so:
child.stdin.write("here you go");
Your exe must be able to wait for stdin in order to process the incoming data.
Related
I know there are lots of questions about this already, but i cant seem to find one that works for me.
I am trying to launch a local file from a local html using cmd to pass command to launch file but it does not seem to work.
This is what i used so far:
<script type="text/javascript" language="javascript">
function RunFile() {
window.open('C:/Windows/System32/cmd.exe /c START %temp%/file.cpl');
}
</script>
someone pls help with this.
Lets just asume i can do this on IE window.open('C:/Windows/System32/cmd.exe); and it will open cmd.
My question is how do i pass some extra argument to make the cmd open my file from another location e.g. window.open('C:/Windows/System32/cmd.exe /c START %temp%/file.cpl');
You cannot run a program using a browser. You might be confused with Windows Scripting JScript, check: https://en.wikipedia.org/wiki/JScript
You may run apps using that (in windows shell). Check this: https://stackoverflow.com/a/15351708/1082061
You could do this using server-side binary execution on Nodejs using child_process.
Pro: Easy to use, just need a simple AJAX call to trigger execution from client to Node server.
Cons: Need to use a server instead of a single HTML page.
I have a EC2 instance, and I would like to write a script (never done them before) so that every time I start my E2 instance in the AWS console, the following files are run automatically.
Lets say I have a file called example.js which contains this:
var test(){
console.log('hello world');
}
test()
And then I have a similar file called example2.js
Everytime I run my EC2 instance, I need to ssh into it and do node example.js and node example2.js in order to run the functions.
However, I would like to write a startup script so that when the EC2 instance state is turned to running (i.e. online), I would like the command node example.js and node example2.js executed by themselves.
Is this possible? If yes, where do I put this script?
I have a Centos image running on my EC2 instance, and the EC2 instance is turned off at night, and turned back on in the morning - hence the script will simplify things!
I read this link, however cannot quite figure it out in my case: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
Any help will be appreciated. Thanks
use pm2. It's an excellent solution for managing node processes. Also can start the processes when you boot the machine.
ref: http://pm2.keymetrics.io/docs/usage/startup/
here is another good tutorials: https://futurestud.io/tutorials/pm2-restart-processes-after-system-reboot
Specific to EC2, you can use the 'User Data' option, available when you create your instance. It takes a script as input that will be executed at launch.
Here's how it looks like :
To add user data to your instance, wait until the night so you don't disrupt yor apps, then right click on it and do "Create Image".
Once the image is created, you can use it to spawn a "new" instance, with user data, and delete the old one without losing anything. Don't forget to reassign the elastic IP of the old instance :)
More information/documentation on aws.amazon.com
I'm writing a Java library, actually, a Clojure library, but for this question, what matters is that it runs on the JVM. This library needs to execute some JavaScript. I tried with Nashorn but I encounter some limitations that might be too hard to overcome. As an alternative, I want to try NodeJS.
I want my library to be self contained, to not depend on the system running NodeJS independently and thus requiring a particular deployment mechanism to place the Java and NodeJS artifacts in the right places to be picked up by the two different network servers. This approach, though, brings some issues.
I will be talking to NodeJS over HTTP but I don't want NodeJS to open a specific port. I want to find a random unused one so there's no collisions. I also want to control where the logs from NodeJS go, as to keep them with the rest of my application. Lastly, my app should be able to detect when NodeJS crashed and re-run it or report an error with information.
What's the best way to approach this? Are there any Java libraries to help manage child process in this fashion? Anything in particular I should do from the NodeJS side (I'm very new to NodeJS, I never used it before).
My solution in the end was to use ProcessBuilder like this:
(defn create-process-builder [js-engine]
(doto (ProcessBuilder. ["node" (:path js-engine)
"--port-file" (:port-file js-engine)
"--default-ajax-host" (:default-ajax-host js-engine)
"--default-ajax-port" (str (:default-ajax-port js-engine))])
.inheritIO))
and then call start in it. inheritIO causes the output of it to go to the output of the current process which effectively merges stdout and stderr.
On top of that NodeJS opens a random port by specifying 0 as the port number and writes it to a file:
(let [app (-> (express)
(.use (cookie-parser))
(.get "/" (fn [_req res] (.send res "Universal JavaScript engine for server side pre-rendering single page applications.")))
(.get "/render" render))
server (.createServer http app)]
(.listen server 0 (fn [] (.writeFile fs (:port-file options) (.-port (.address server)))))))))
which then is opened by the Java side (waiting for it to appear):
(defn get-port-number [js-engine]
(or (with-timeout
(:start-timeout js-engine)
(loop [port-number (read-port-file js-engine)]
(if (string/blank? port-number)
(if (is-running? js-engine)
(do (Thread/sleep 100)
(recur (read-port-file js-engine)))
(throw (Exception. (str "While waiting for port number, process died: " (:path js-engine)))))
port-number)))
(throw (Exception. (str "Waited for " (:start-timeout js-engine) " for " (:path js-engine) " to start and report its port number but it timed out.")))))
There is a pretty good answer here on how to run javascript in java. Would something like that be doable for your case? If not here are some resources:
Random port in nodejs You could hit yet another service to find an open port during the build, or have your node app fire an http request to your java server based on the port it grabs.
Winston is the best logging library I've found, you shouldn't have any issues logging to the same path.
Forever and PM2 are the common node process managers which keep node running. I currently prefer forever (not sure why)
It sounds like you will be using a lot of cpu within node. If that is the case you will probably want to use the cluster module (so nodejs can utilize multiple cores). If you block the event loop (which cpu based processing will, then you will only be able to perform 1 concurrent request per forked process).
I have been in a similar position where I had to run fortran from a python script, so here is my two cents. Run your node.js script with a terminal command in Java like this:
Runtime rt = Runtime.getRuntime();
String[] commands = {"node example.js", "args"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
With setup you can pass in parameters to your node program and get responses. Although I am not sure what you are using your node.js program for, so not sure if this is helpful.
Nashorn does have some issues that I've run into as well, such as finding information about some of their APIs (documentation leaves a lot to be desired), and the slow boot up.
What I would recommend instead: treat your server-side rendering as a service and not a child process.
In other words, you could run a Node.js instance on your internal net on say port 10015 and only allow local connections to it (you could also send logs wherever you want). Then you can make a request to the service with the pages that you want to render, such as localhost:10015/posts/ and have that Node.js app render the page inside of a headless browser (using something like Phantom or Slimer).
To keep your Node server up, you can use Forever or supervisord, and to help you gain traction faster, you could look at what the Prerender team has made:
https://github.com/prerender/prerender-node
I have a set of database administration tasks that need to run after some other rake tasks. So I read the Ruby Mongo driver source and a few blog posts and I ended up with this code:
scr = open("./scripts/update_stats.js", &:read)
db = Mongoid::Config::master
result = db.command({:$eval => scr})
logger.debug result
logger.warn "Finished updating stats"
In the script I have several functions and then one final one:
r = update_stats();
print("update result:");
print (r);
Ok, so it's all running fine when I run it directly via the command line. Well, it seems to be. But I'd like to take the result value and stow it into my logs. I could store the value into the database and then pull it out I suppose. Seems like there should be a better way. What I do get it my logs is:
DEBUG 2012-01-03 22:27:03 -0800 (21392) {"retval"=>nil, "ok"=>1.0}
That doesn't tell me much other than that it didn't blow up. So, how can I get the returned value of update_stats and log it in my Ruby code?
OK, so there are two potential issues here.
The first issue is that you are running a JS file against the database, but I'm not really clear how this works. It looks like some special feature of Mongoid? What result are you expecting?
The second issue is that it's not clear why you're using a JS file at all if the rake machine has driver access. What commands are you running that cannot be simply run as commands via the Ruby driver directly?
In general, the only time you need to bring in an arbitrary JS file is when you're calling jobs directly via the mongo program. So you would run mongo my_map_reduce.js from a cron job and this would make sense.
If the commands you're running are accessible via the driver (this is true 99% of the time). Then just write the whole admin script in Ruby.
I want to run an external program in XPCOM but I need to get the actual return string from the program, not just a return code. How would I do this?
All I've found is nsICommandLine, nsICommandLineHandler, nsICommandLineRunner and nsIProcess none of which return anything beyond an exit code (from what I can see).
Gecko doesn't have any meaningful IPC capabilities. While the process is running you can communicate with it via TCP sockets. If you want to return something when the process finishes - write to a file and your Firefox extension can read out that file then.