I want to make a two way communication model for JavaScript and Python. I want JavaScript to process a data and send it to Python and then Python processes it and sends it back to JavaScript. I don't have a clue how this can be achieved and how the communication between the two languages will be made.
Consider the example:
Read the comments for clarity of the model!
var files = [];
const div_files = document.getElementById("files");
const div_results = document.getElementById("results");
function fetchNames() {
div_files.innerHTML = ""; // clears the file div
div_results.innerHTML = ""; // clears the results div
var checkbox_elements = document.getElementsByClassName('filename');
Array.from(checkbox_elements).forEach(function(k) {
if (k.checked) {
files.push(k.value);
div_files.innerHTML += k.value + '<br>';
}
});
// the files array should now be shared with python
//console.log(files);
// JavaScript SHOULD WAIT while PYTHON processes the data and shares the cal_array with JS
// when the cal_array is available with JS only then it shall start processing the code mentioned below
var cal_array = [
[2231, 11640, 104621],
[2231, 11640, 104621],
[9, 494, 3339]
];
Array.from(cal_array).forEach(function(k) {
div_results.innerHTML += k + '<br>';
})
};
<form>
<input type="checkbox" class="filename" value="./first.html">First File<br>
<input type="checkbox" class="filename" value="./second.html">Second File<br>
<input type="checkbox" class="filename" value="./third.html">Third File<br>
<br>
<input type="button" value="Submit" onclick="fetchNames()">
</form>
<br>
The selected file(s) are:
<div id="files"></div>
<br> The result shows the number of lines, words, and characters of the respective files mentioned above:
<div id="results"></div>
The Python Script is as follows:
import os
files = ['./first.html','./second.html','./firstfile.txt'] #this array should be passed into python by the JS script
cal_array = [] #this array should be shared with JS after data has been entered into it
def calculation(): # this function calculates the number of lines, words and characters of the selected file(s)
for val in files:
file_details = []
fname=(val)
infile=open(fname, 'r')
lines=0
words=0
characters=0
for line in infile:
line = line.strip(os.linesep)
wordslist=line.split()
lines=lines+1
words=words+len(wordslist)
characters=characters+ len(line)
file_details.append(lines)
file_details.append(words)
file_details.append(characters)
cal_array.append(file_details)
calculation()
print(cal_array)
# some code here to share cal_array with javascript
I'm a noob in Python, but I want to know how to make the two languages interact with each other? I'll really appreciate any help!