Javascript and MongoDB - write to file - javascript

I'm using mongoDB on an ubuntu server. However I'm using a javascript to store data and do some map/reduce. I would like to measure these operations and write the results into a file. Somehow I fail to open a file and write into it.. I tried the following:
f = new File("myfile.txt");
if(f.open("w") == true)
{
f.write("test");
f.Close();
}

The file object within spidermonkey (the JS engine MongoDB uses, and coincidently the console) has been made obsolete: https://developer.mozilla.org/en-US/docs/SpiderMonkey/File_object . Not only that but it wasn't standard to spidermonkey anyway so that was a long shot.
As #gkamal states, the best way is to pipe the output of the MongoDB console like so:
mongo someprocess.js > outpout

Simple answer: you can not write files using Javascript.

It is probably better to write to the console using println and redirect the output to file, pass the javascript file as a parameter to mongo.
mongo someprocess.js > outpout

Related

Call Python script from local JavaScript App

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!

How to call JavaScript function from PHP file

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.

Bash/PHP/Javascript: How to run a php file that outputs javascript, and execute that javascript? [duplicate]

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

Run python or javascript file from postgres function?

How i can Run python or javascript file from postgres function ?
I have two postgres data base with totally different structure .
but i need to sync that two databases .
I will write the script that will read data from local data base and write into server data base in any language (python , java , javascript, node).
but the main problem is :
I do not know how to call that script from postgres procedure or function .
so the ques is :
How we can call or run any script from postgres procedure ?
Use plperl, plpython or pljava and use the system utils of the language. I.e in plpython use subprocess, in java use Runtime.getRuntime().exec and so on:
For example in plpython:
CREATE LANGUAGE plpythonu; -- create language if does not exist
CREATE OR REPLACE FUNCTION venue.test_execute()
RETURNS void AS
$BODY$
import subprocess
subprocess.call(['/path/to/script/test.py'])
$BODY$
LANGUAGE plpythonu;
SELECT venue.test_execute();
CONSIDERATIONS
Actually you can launch a script from a Postgres function, but this is not the preferred way to synchronize data between databases. You probably will have issues related to absolute and relative paths to scripts and data, and file system permissions. Instead use a database function to export data in a known format and call your synchronize script from outside the database. Another options is use the dblink module.
You can create a Perl Function and in that call your script to sync the databases.

extract the value of an array in an existing javascript file

I'm trying to convert values defined in a javascript file to a json file or extract those values to some other format that I can process with python. Does anyone know of a python library, node.js package or other method for doing this with a local file? I cannot use ajax or php for this task.
Context:
I have a javascript file called file.js, in which there are no functions, but a number of lengthy arrays defined in the following fashion:
var an_array1 = new Array();
an_array[1] = {some array values 1}
...
an_array[n] = {some array values n}
var another_array = new Array();
another_array[1] = {some other array values 1}
...
another_array[m] = {some other array values m}
No functions are included in this file, just the calls to var and the subsequent setting of the array values.
Similar questions provide answers that focus around using ajax or php, but I do not think I can use these tools for this purpose. I can, however, use node.js, python and any associated libraries/packages. I would also be game to try an awk/sed type script, but I don't think this will work here, since the data I want requires file.js to be parsed/processed first.
Ideal outcome
Ultimately, I'd like to use some method to process the file.js, extract the value of one particular array to its own file as JSON, or some other, similar format (XML would be fine too, even csv would work). e.g.:
file.json:
[{some array values 1},...,{some array values n}]
Does anyone know how this might be done? There are some questions similar to this, but those assume that I am querying a website or something, which is not the case here.
Here's a node file that could do this for you if the file.js file is structured to declare the desired variables at the top level. If that isn't the case, you will have to show us what exactly file.js looks like.
// load filesystem module
var fs = require("fs");
// read JS file and execute it
var data = fs.readFileSync("file.js", {encoding: "utf8"});
eval(data);
// write data out to files
fs.writeFile("result1.json", JSON.stringify(an_array1));
fs.writeFile("result2.json", JSON.stringify(an_array2));
You would then just run this JS file with node.js.
This would use the V8 JS interpreter in node to parse the JS file with your variables in it. It would then load the file system module and then write the JSON representation of two separate arrays out to files.
You can then write Python to read those files, parse the JSON into a form Python understands (Python has JSON parsing built-in) and then do whatever you want with the data in Python.

Categories