I need to be able to execute a shell command through javascript, similar to the php function "exec()". I understand that this may be impractical in javascript because of security reasons, but my javascript code is running on the server, and no clients have direct access to the file.
Users make a request to the server for some data, and the server-side javascript code is called. From the javascript file, I need to execute a program in order to gather data based on user input, then pass this data back.
If this isn't possible in vanilla Javascript, please point me towards a library or tool that can do this, preferably in javascript/frameworks on javascript.
JavaScript has no 'exec' function like PHP does. It's all because JavaScript runs on the client and don't have access to the server part.
However you can create PHP page and send AJAX requests to it to execute particular command.
ALTHOUGH, you need to be VERY, VERY and VERY cautious about which commands to run.
It's very dangerous to do like that. I don't advice you to do like that, however, it's possible.
Good luck!
If it's client side - You can't
If it's node.js:
var exec = require('child_process').exec;
child = exec("command", function (error, stdout, stderr)
{
// handle the output
});
This might be what you're looking for: https://github.com/arturadib/shelljs
Or, if you want to have direct access to commands, perhaps this will help: http://nodejs.org/api/child_process.html
Related
so I've looked around quite a bit now and wasn't able to find quite the use case I think I am confronted with.
For some background:
I'm fairly new to JavaScript and have never had to call any other program/script from it. Now I did develop a Python script that pulls some data from online sources, formats it and dumps it into JSON files. In order to display this data in a proper way I figured I would use Electron.
While handling the JSON files is completely fine (would be quite sad if it wasn't I guess), I need to be able to call the Python script updating the data from my Electron UI. As everything is local, I hoped, that there would be an easier way, than setting up some server for the Python script to run on, just to be able to trigger its execution from my Desktop App. This is especially true, as I don't even need to get or process any returns, I just want to trigger the execution of that script.
So the question now is: is there such an "easy" way to execute Python scripts from an Electron/JavaScript based locally saved Desktop app?
Thanks in advance for any answers!
Like a previous commenter mentioned, you should be able to follow this SO answer in Node.js (which is what Electron uses).
To expound upon that answer just a bit, I'd recommend using the built-in Python JSON utility to dump JSON to the standard out (just printing out the JSON string), and the using the built-in Node.js JSON utility to parse that JSON string into a javascript object for use in your application.
Alright, so after being redirected to this thread, which I can only recommend reading through if you have an interest in this issue, I took their solution and altered a little, which took me a bit of time, due to some confusion, which I now would like to spare you guys!
To re-introduce the issue: The goal is to call a python script from a JavaScipt/Electron based UI. The python script only needs to be executed, but it needs to happen onClick, as it is an update function.
Now this is the code I used:
const exec = require("child_process").exec;
function triggerUpdateAndRefreshFooter() {
exec('python relativePathToScript/update.py',
function(error, stdout, stderr) { //callback function, receives script output
refreshFooter(); //don't use the output, but I could here
}
)
}
I did have some issues figuring out all of that const stuff in the other thread, as well as having to guess IF I could just execute my script in a separate function. In the end this did work!
I hope this was helpful!
I have a JavaScript file on my server that contains a function. I would like to develop a REST Api to connect to this server, run the JavaScript function and send back the output.
Is it possible to call a JavaScript function from a php file?
I read this but it doesn't answer my question, because my js file is hosted on the same server as the php file.
Is the V8Js extensions what I am looking for?
Edit
The js function looks like this:
function (line, userWeight, weightunit){
//logic is here
var computed = {
userLengthFtin: userLengthFtin,
userLevel: userLevel,
proId: line['id'],
proLengthFeetin: proLengthFeetin,
proThick: proThickFtin,
weightunit: weightunit
};
return computed;
}
Is it possible to call a javascript function from a php file ?
You would need to hand things over to some other software which can execute JS. This might be through shelling out or it might be though a library such as Selenium or the V8js library you found.
Whatever you choose, it would need to be able to handle the particular needs of the JS (e.g. if the JS expects to be embedded in a webpage with access to a DOM and all the APIs provided by a web browser, then you couldn't simply run it with Node.js).
It would probably be simpler to rewrite the function in PHP.
I have php file that is to be executed as cronjob, this php file contains some javascript.
I will explain the flow :
the Php is used to retrive some data(A LIST OF URLS) from DB.
For each URL Obtained, a Java script API is used.
THe result Obj returned from API contains data for each url.
The data is then sent back to as an AJAX Call for each url to a php file .
Can this be implemented Via CRON JOBS ?
OR
Is there any method to schedule javascript to run periodically, like cron for php?
UPDATE: i could manage the javascript call to API with PHP curl ,And the cron Job is getting executed perfectly. But i dont think it is the correct solution to this question may be Node.Js is the solution(i didnt test it yet).
You can't run Javascript in Cronjobs because Javascript is ran by browsers. I think you should take a look at curl in php to call an api instead.
http://www.php.net/manual/en/book.curl.php
You have to split the work: Cron the JS, Cron the PHP. In the middle, deliver one's results to another. Agree with phantomjs usage for JS execution (or casperJS-I prefer). Execute the JS, output to JSON as a file, read from the file using file_get_contents from PHP. And define these actions in two different cron jobs.
You can run Javascript via cron in a Javascript runtime like node.js: http://nodejs.org/
phantomjs is one possibility, see this thread wget + JavaScript?
Otherwise you could run Node.js on your server to execute JavaScript in a CLI type environment but mixing node.js and PHP could become complicated.
you can schedule javascript with cron by using Node.js
I made a website where I can write code into a textfield and I want to send this code to my nodes.js server and call R, which is installed on my server, and make it process the written R code.
What I have trouble with is, how can I start R on my server and input code into it via Javascript?
The security aspects are not relevant for this because it will never go live and will always stay localhost.
Any ideas on how to approach this problem?
If you use an R web framework, you can then use the eval function to run the contents of the text box as code.
Obviously, this is very risky, but you've said you only want this to run locally.
You could use other languages with an exec function to spawn a child process. Write the code to file, compile with exec, then run with the exec function.
In node you could use a child process to achieve this
https://nodejs.org/api/child_process.html
In PHP you could use exec to the same end
http://php.net/manual/en/function.exec.php
All of these options carry the same risk.
If you want to safely execute R code on the server, you could implement an RPC mechanism, a simple one would consist of the name of the command and the parameters to be passed. This way, you can effectively whitelist what is allowed to execute, but it does mean you can't excecute arbitrary R code.
I have a question about compiling server side functions in PHP with Ajax. I am trying to understand what happens when multiple asynchronous calls are made to the same server side script.
Lets say that I have the following php script - "msg.php":
<?php
function msg(){
$list1 = "hello world";
return $list1;
}
echo json_encode(msg());
?>
and call Ajax JQuery like this:
function get_msg() {
$.get("msg.php", function(data){console.log(JSON.parse(data));}) }
with a button in html:
input type="button" onclick="console.log(get_msg());" value="Submit" class="btn btn-info"
Assuming that everything works I am trying to understand the following:
Does the server recompile the "msg" php function each time a user clicks the button? Does it (or can it?) manage this by user? How about by session?
After multiple clicks by different users does the server destroy the "msg" function after each request? Can I save multiple versions of the same function in memory for later use? If so is it possible to reconcile the different versions?
Is there a way to pre-compile a single php function for all Ajax requests?
Is there a "proper" way to handle dynamic function calls on the server side?
I feel like recompiling it on the server side is wasteful but perhaps this is how things are supposed to work.
PHP interprets code on each request. But there is OPcache:
OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.
This extension is bundled with PHP 5.5.0 and later, and is available in PECL for PHP versions 5.2, 5.3 and 5.4.
You can find here on SO how to enable OPcache:
Add the following line to your php.ini:
zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)
... and much, much more!
I think what you're looking for is caching. PHP by default is a scripted language so if you need to reference something repeatedly it will be executed each time since its interpreted not compiled. Caching is a way around that.
There are a few ways I can think of to store this data for later use. One is cacheing in plain text. Write out your result to a text file and then reference that for later use, using the last modified date as a way to check for freshness. I'm not a big fan of this method because I think having extraneous files written to the server is messy. (just my opinion)
http://php.net/manual/en/function.file-put-contents.php
Thats the function you would use to store your result.
Another option is writing to a database for the results and then time stamping it so you can reference that for freshness. From there you could just use PDO or mysqli to retrieve the data. Then you could use a database cache to make the response time more performant.
Another option is just using something like OPCache to store the results of the function in memory on repeated calls. ( I don't have much experience in this though )
Hopefully that puts you in the right direction.