(server.js) I have following code to run my server -
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './public/index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('500 Internal Server error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8000);
console.log('Server running at http://localhost:8000/');
(index.html) And my index.html file inside public directory is following -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript" src="./algebra.js"></script>
<script type="text/javascript" src="./math.js"></script>
<script>
//Some more code ...
function runPythonCode(x, y){
//process python file and get result
}
runPythonCode(2, 3);
</script>
</body>
</html>
In above code inside runPythonCode function I want to pass variable x and y to my python code and do some processing with x and y and want the value return back to javascript.
I was simply tried like this inside the script tag in index.html just to check if python script is running or not -
text = "hello"
$.ajax({
type: "GET",
url: "./app.py",
//data: { param: text}
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
})
And my aap.py python code -
import csv
from numpy import matrix
def main():
x =2
return x
if __name__ == "__main__":
x=main()
But after running this code I am simply getting whole python code inside console. What I am doing wrong here? How to run python file inside js?