I want to call Python in Node.js and use SymPy module - javascript

I use Node.js and Express as server side language.
And I made a website using AWS.
I need to use Python because I need complicated calculations.
However, I don't know how to call Python from Node.js.
Please tell me how to use Python's SymPy module in Node.js.

In case you need to call a external script from your Node.js application, you can always spawn a process to do so.
There is (obviously) a npm module to make it easier for you to use a python script from Node.js. You can use python-shell module to launch your "complicated calculation" scrip if you're not able to find the equivalent in Node.js ecosystem.
Here a basic example inspired by the SymPy & python-shell documentation:
script.py
from sympy import *
x = Symbol('x')
print (limit(sin(x)/x, x, 0))
app.js
const {PythonShell} = require('python-shell');
PythonShell.run('script.py', null, function (err, res) {
if (err) throw err;
console.log(res[0]); // 1
});
Also pay attention to have the SymPy module in your path.

Related

PYTHON module "requests" not working with packaged electron app

In my electron app I have a python file that has two import statements shown below
import requests
import shutil
The app works fine without an errors in the IDE but after packaging the electron app with
npx electron-packager ./ --platform=darwin --icon=src/img/logo.icns
The app gives me this error
It only gives this error for the 'requests' module but not the 'shutil' module. And yes, 'requests' is installed on my computer. I also use the PythonShell module in the js file to run the python file like below
function version_checker(){
form.classList.toggle('hide');
circle.classList.toggle('show');
let pyshell = new PythonShell(__dirname + '/version_checker.py');
pyshell.on('message', function (message){
console.log(message);
if(message !== "same"){
console.log("updating")
}
else{
if(message !== "restart"){
form.classList.toggle('hide');
circle.classList.toggle('show');
}
else{}
}
})
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
});
}
I also do not wish to compile the python file into an executable because the python script "talks" to the js file. I am also on a M1 Pro Macbook running macOS Ventrua if that helps
How do I package the app and include the 'requests' module OR How do I make the 'requests' module work with the packaged app
I did find a stackoverflow post that asked a similar question but the owner voluntary took down the question so I wasn't able to view it
I looked at this post but it wasn't helpful because I'm not using 'anaconda' or 'child-process'
PythonShell just calls the system's Python interpreter, so use PIP to install the requests library
Or specify the interpreter as follows:
new PythonShell(__dirname + '/version_checker.py', {
pythonPath: '/path/to/python'
})
Note: For production purposes, it is recommended to include an interpreter in electron and install dependencies
It seems you just want to make a HTTP request, why not try fetch in javascript?
If the error is ModuleNotFoundError, then your python interpreter is struggling to find the requests module. This can happen for a number of reasons:
Module does not exist: We can rule this out if your ide ran program successfully.
2: Module is not where interpreter expects to find it: Most likely.
Almost certainly the python interpreter used by your IDE is different to the one you ran after packaging the electron app.
The solution is to either:
a. make sure the location of requests is visible to the PYTHONPATH by setting that in the proper location (I don't use MAC but I believe you have ~/.bash_profile file to set it in or
b. Explicitly add the request module location via a sys.path.append command in your code eg
import sys
import os
path = 'your path to request module'
sys.path.append(os.path.join(path, 'requests')
import requests
You should be able to find the path location by investigating your IDE and looking where you set the module to be included in your program

Why is require module in JavaScript not able to import the fs library?

The javascript code is as follows:
const fs = require('fs');
function init() {
alert("Done!");
}
init();
While executing the Javascript code, I am not able to get the alert Done! on my webpage. On further analysis I came to a conclusion that it is most probably because the require statement is not working (there was an alert when I commented the require statement). Why is it so?
require is not available in the browser but is used in NodeJS. If you want to use it in your browser, you'll need a building tool like Browserify or Webpack.
By the way, the File System package is available in NodeJS only.

require is not defined? Node.js [duplicate]

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 5 months ago.
Just started working with Node.js. In my app/js file, I am doing something like this:
app.js
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');
console.log('running server!');
When I'm in my terminal and run node app.js, the console spits out 'running server!', but in my browser I get, Uncaught ReferenceError: require is not defined.
Can someone explain to me why in the terminal, it works correctly but in the browser, it doesn't?
I am using the node's http-server to serve my page.
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.
To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.
In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.
node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().
require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().
There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).
But, you won't be running a web server in your browser as that is not something the browser has the capability to do.
You may be interested in browserify which lets you use node-style modules in a browser using require() statements.
As Abel said, ES Modules in Node >= 14 no longer have require by default.
If you want to add it, put this code at the top of your file:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.
See browserify or webpack if you wish to serve browser-specific modules from Node.
Just remove "type":"module" from your package.json.
I solve this by doing this steps:-
step 1: create addRequire.js file at the project root.
step 2: inside addRequire.js add this lines of code
import { createRequire } from "module";
const require = createRequire(import.meta.url);
global.require = require; //this will make require at the global scobe and treat it like the original require
step 3: I imported the file at the app.js file head
import "./start/addRequire.js";
now you have require beside import across the whole project and you can use both anywhere.
Point 1: Add require() function calling line of code only in the app.js file or main.js file.
Point 2: Make sure the required package is installed by checking the pacakage.json file. If not updated, run "npm i".
My mistake: I installed ESLint to my project and made a mistake when I filled out the questionnaire and chose wrong type of modules)
Maybe it will be helpful for someone))
What type of modules does your project use? ยท * commonjs
I solve it, by removing below line from package.json file
"type": "module"
Hope it will solve the problem.

Nodejs library without nodejs

How can I integrate a nodejs library into my non nodejs project?
I am particularly needing this library:
https://github.com/greenify/biojs-io-blast
BioJS uses Browserify CDN to automatically generate a single JS file for usage. Either include
<script src="http://wzrd.in/bundle/biojs-io-blast#latest"></script>
in your html or download the JS file via this link.
We also have a live JS Bin example here.
Yes, you can do it using a Publisher/Subscribe pattern and a Queue library, such as RabbitMQ.
In the example below, the author is communicating a python script with a NodeJS one, using the RabbitMQ clients for each platform.
https://github.com/osharim/Communicate-Python-with-NodeJS-through-RabbitMQ
The code for sending from NodeJS:
var amqp = require('amqp');
var amqp_hacks = require('./amqp-hacks');
var connection = amqp.createConnection({ host: "localhost", port: 5672 });
connection.on('ready', function(){
connection.publish('task_queue', 'Hello World!');
console.log(" [x] Sent from nodeJS 'Hello World!'");
amqp_hacks.safeEndConnection(connection);
});
Then, receiving in python:
#!/usr/bin/env python
import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
#our callback
def suscriber(ch,method , properties , body):
print "[Y] received %r " % (body,)
time.sleep( body.count('.') )
print " [x] Done"
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(suscriber, queue = 'task_queue')
print ' [*] Waiting for messages from Python. To exit press CTRL+C'
channel.start_consuming()
to integrate any node library you use the package manager NPM https://www.npmjs.com/ so to integrate your library do as follow
open terminal
cd path/to/your/project_dir
type this line
npm install biojs-io-blast
This is the more common use case. Some of the node.js libraby, i like them too much i want to use it everywhere. But this library, what i see uses core modules of node.js like fs. I dont think you can use it without node dependency || node binary. But as Code Uniquely or others folks says, if you are using webpack as a build/dev. You can try, browserify or BioJS
The node_module which provided is kind of xml parser. You can't add nodejs library (node_module) to non nodejs programs. You can get xml parser for Blast depending on kind of programming language you are using.
For example :
For PHP phpBlastXmlParser and
For java this might helpfull

Problems concerning require() javascript

I'm trying to run the JavaScript client for the Tumblr API but I'm getting a "require not defined" error. I've scoured almost every corner of SO trying to find a way to make it work.
I've managed to use Browserify to recognize it but at some point, I'm getting a fs.readFileSync error.
Then I tried RequireJS and again it does the require thing but I'm getting a Module name "something" has not been loaded yet for context"
I'm really new to Node.js but if I'm understanding it correctly the require() part isn't something the browser can do right? Can anyone guide me as to what solutions I can take for this? If it helps, I'm not planning to upload this on a server or anything. I'm just trying to run it on my local computer and just planning to run the API locally.
Edit:
Here's what I have on my main.js
var tumblr = require('index.js');
var client = tumblr.createClient({
consumer_key: '<consumer key>',
consumer_secret: '<consumer secret>',
token: '<token>',
token_secret: '<token secret>'
});
// Show user's blog names
client.userInfo(function (err, data) {
data.user.blogs.forEach(function (blog) {
alert('dang');
});
});
When I try requirejs, I do this to reference it <script data-main="script/main" src="scripts/require.js"></script>
It seems to me that you might be confusing server-side JavaScript (Node) and client-side JavaScript (in the browser). The Tumblr API you're trying to use is for Node only; you can't run it in a browser. You have to:
Install NodeJS and NPM on your system
npm install tumblr.js
Run the script with node <script name>
Start with the Tumblr.js example script, then customize for your own purposes!

Categories

Resources