using python modules in node.js

  • Last Update :
  • Techknowledgy :

How are we going to write cross-language modules?,Now we can use it from our Python code with from ng_annotate import ng_annotate and calling that function, but let's also make it a convenient command line tool:,Learning CenterBlogGet insights on scaling, management, and product development for founders and engineering managers.Community PostsRead programming tutorials, share your knowledge, and become better developers together.Hot TopicsAndroidAngulariOSJavaScriptNode.jsPythonReactBlockchainEthereum,Next, we will need to be sure that if someone installs this, it will have access to the node module ng-annotate. So, create a file called package.json, and put this in it:

So to start lets use pip to install the pyexecjs library:

$ pip install pyexecjs

Next we will start our module file (which we will call ng_annotate.py) by importing the get function from execjs, which allows us to request a specific JavaScript engine to run our code.

from execjs
import get
import os

runtime = get('Node')

Next, we will need to be sure that if someone installs this, it will have access to the node module ng-annotate. So, create a file called package.json, and put this in it:

{
   "dependencies": {
      "ng-annotate": "*"
   }
}

Now we can call the annotate function from our Python code with
context.call('annotate',*args), and it will return the result just like it would in the JavaScript. So to make that into a standard Python function we can use, it's as easy as:

def ng_annotate(src, cfg = None):
   if cfg is None:
   cfg = dict(add = True)
return context.call('annotate', src, cfg)

Now we can use it from our Python code with from ng_annotate import ng_annotate and calling that function, but let's also make it a convenient command line tool:

import sys

def main():
   print ng_annotate(open(sys.argv[-1], 'r').read())

if __name__ == "__main__":
   main()

Suggestion : 2

Third party modules can be downloaded through the npm. These types of modules are created by the open node js developer community and are available for download at:,There are three main types of modules in node.js:,In order to use Node.js core or NPM modules, you first need to import it using require() function. Let’s say you want to import http as your module then you do the following as shown below:,Every module is different from each other and hence should not overwrite or hinder other modules functionalities so that they can be used serving their purpose inside a node.js application.

You can create your own modules by creating them locally in node js by creating javascript files, let’s create a new file as ‘local.js’ and add the following code into it to see the current time and date of your local machine:

function timeanddate() {
   var date = new Date();
   var n = date.toDateString();
   var time = date.toLocaleTimeString();

   console.log('date:', n);
   console.log('time:', time);
};
timeanddate();
module.exports = timeanddate

After creating a javascript file as a module, we will import it in an another file ‘app.js’ where we will use the require function. If local.js file is present in the same directory of app.js then you can define the path of ‘local.js’ as:

var localmodule = require('./local.js');
console.log('Using Local Modules');

Use the (./) notation to fetch the local module file. The result of the above will be:

Hiras - MacBook - Air: ~Hira$ node app.js
date: Thu May 07 2020
time: 5: 03: 51 AM
Using Local Modules

As you can see above, this is how we can import the core module ‘http‘ by using the require() function; we also use the variable to store the required module. We will further create a server using the http module by using the following code:

var http = require('http');

http.createServer(function(req, res) {
   res.writeHead(200, {
      'Content-Type': 'text/html'
   });
   res.end('Hello World!');
}).listen(3200);

After importing the http module, we will use the createServer() function and send two arguments(could be any) req and res to fetch the request first so that the server will return with a response of ‘Hello World‘. Run ‘node file_name.js’ code on your terminal or command prompt:

node firstapp.js

Suggestion : 3

Installation

npm install node - calls - python

Install Node

sudo apt install curl
curl - sL https: //deb.nodesource.com/setup_13.x | sudo -E bash -
   sudo apt install nodejs

Install Python

sudo apt install python3
sudo apt install python3 - dev

Install Node-gyp if missing

npm install--global--production windows - build - tools
npm install - g node - gyp

Mac: install XCode from AppStore, NodeJS and Python

npm install node - calls - python
import numpy as np

def multiple(a, b):
   return np.multiply(a, b).tolist()
const nodecallspython = require("node-calls-python");

let py = nodecallspython.interpreter;

py.import("test.py").then(async function(pymodule) {
   let result = await py.call(pymodule, "multiple", [1, 2, 3, 4], [2, 3, 4, 5]);
   console.log(result);
});
const nodecallspython = require("node-calls-python");

let py = nodecallspython.interpreter;

py.import("test.py").then(async function(pymodule) {
   let result = py.callSync(pymodule, "multiple", [1, 2, 3, 4], [2, 3, 4, 5]);
   console.log(result);
});
import numpy as np

class Calculator:
   vector = []

def __init__(self, vector):
   self.vector = vector

def multiply(self, scalar, vector):
   return np.add(np.multiply(scalar, self.vector), vector).tolist()
const nodecallspython = require("node-calls-python");

let py = nodecallspython.interpreter;

py.import("test.py").then(async function(pymodule) {
   let pyobj = await py.create(pymodule, "Calculator", [1.4, 5.5, 1.2, 4.4]);
   let result = await py.call(pyobj, "multiply", 2, [10.4, 50.5, 10.2, 40.4]);
});

Suggestion : 4

Run Python Script using PythonShell from Node.js,Run Python script from Node.js using child process spawn() method,This is the simple implementation of a how-to run python script with Node.js which can be useful in situations where you have a stack of Node.js application and you want to run a simple python script. If you want to know more about PythonShell module, then go through the given link.,Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

After saving both the files, run the following command from its root folder : 

node test.js