{"id":132353,"date":"2022-09-20T12:00:09","date_gmt":"2022-09-20T16:00:09","guid":{"rendered":"https:\/\/blog.logrocket.com\/?p=132353"},"modified":"2024-06-04T17:04:47","modified_gmt":"2024-06-04T21:04:47","slug":"exploring-jspybridge-library-python-javascript","status":"publish","type":"post","link":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/","title":{"rendered":"Exploring JSPyBridge, a new library for using Python in JavaScript"},"content":{"rendered":"<!DOCTYPE html>\n<html><p>Node.js and Python are two of the most popular tools for developing software. Each has its pros and cons, and sometimes it can be difficult to choose from them, depending on the task at hand. For example, the Node.js runtime is fast and has a large community with millions of packages, but it pales in comparison to Python when it comes to data science and machine learning packages.<\/p><img loading=\"lazy\" decoding=\"async\" width=\"730\" height=\"487\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png\" class=\"attachment-full size-full wp-post-image\" alt=\"Exploring JSpyBridge, a new library for using Python in Javascript\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript-300x200.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\">\n<p>Depending on your problem, you might find yourself needing both Node.js and Python; however, the languages are distinct from one another and do not have any mechanism to communicate.<\/p>\n<p>To remedy this, <a href=\"https:\/\/github.com\/extremeheat\/JSPyBridge\" target=\"_blank\" rel=\"noopener\">JSPyBridge<\/a> was created to allow Node.js and Python to interoperate. Language interoperation allows Node.js and Python to work together as if they are part of the same system and share data structures. With JSPyBridge, you can import and use Python API methods in Node.js as if they are native, and vice versa.<\/p>\n<p>In this tutorial, we will use JSPyBridge to interoperate between Node.js and Python. In the first half, we will look at how to access and use Node.js functions, packages, classes, and arrays in Python. In the second half, we will look at how to use Python functions, modules, classes, and arrays in Node.js.<\/p>\n<p><em>Jump ahead:<\/em><\/p>\n<ul>\n<li><a href=\"#what-is-jspybridge\">What is JSPyBridge?<\/a><\/li>\n<li><a href=\"#accessing-javascript-python\">Accessing JavaScript in Python<\/a>\n<ul style=\"margin-bottom: 0px; padding-bottom: 0px;\">\n<li><a href=\"#importing-javascript-function-python\">Importing a JavaScript function in Python<\/a><\/li>\n<li><a href=\"#importing-using-node-js-packages-python\">Importing and using Node.js packages in Python<\/a><\/li>\n<li><a href=\"#using-es2015-python\">Using ES2015 classes in Python<\/a><\/li>\n<li><a href=\"#using-javascript-iterables-Python\">Using JavaScript iterables in Python<\/a><\/li>\n<li><a href=\"#importing-javascript-file-python-different-directory\">Importing a JavaScript file in Python from a different directory<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#accessing-python-node-js\">Accessing Python in Node.js<\/a>\n<ul style=\"margin-bottom: 0px; padding-bottom: 0px;\">\n<li><a href=\"#importing-python-function-node-js\">Importing a Python function in Node.js<\/a><\/li>\n<li><a href=\"#working-python-third-party-modules-node-js\">Working with Python third-party modules in Node.js<\/a><\/li>\n<li><a href=\"#using-python-classes-node-js\">Using Python classes in Node.js<\/a><\/li>\n<li><a href=\"#using-python-iterables-node-js\">Using Python iterables in Node.js<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h3>Prerequisites<\/h3>\n<p>To get the most from this tutorial, you should have:<\/p>\n<ul>\n<li>Node.js v \u2265 14 installed on your computer<\/li>\n<li>Python v \u2265 3.8 installed<\/li>\n<li>Basic knowledge of how to use Node.js and Python<\/li>\n<\/ul>\n<h2 id=\"what-is-jspybridge\">What is JSPyBridge?<\/h2>\n<p>JSPyBridge is a bridge that allows Node.js and Python to interoperate. You can think of it as a literal bridge that sits between two programming languages, taking data or objects from one language and transforming them so that the language on the other side can parse them.<\/p>\n<p>Some of the objects that can be shared between Python and Node.js are functions, classes, iterables, and callbacks. When using JSPyBridge, for example, you can import a function from Python into Node.js, invoke it, and access the return value in Node.js.<\/p>\n<p>Here is a brief overview of JSPyBridge\u2019s features:<\/p>\n<ul>\n<li>Garbage collection<\/li>\n<li>Extending and invoking classes<\/li>\n<li>Support for callbacks, functions, classes, and iterables<\/li>\n<li>Importing local files<\/li>\n<li>Managing errors<\/li>\n<\/ul>\n<p>For more features, see the <a href=\"https:\/\/github.com\/extremeheat\/JSPyBridge#bridge-feature-comparison\" target=\"_blank\" rel=\"noopener\">Bridge feature comparison<\/a> table.<\/p>\n<h2 id=\"accessing-javascript-python\">Accessing JavaScript in Python<\/h2>\n<p>In this section, we\u2019ll look at how we can access Node.js functions, packages, classes, and arrays in Python. To do this, we will create a project directory and download the <a href=\"https:\/\/pypi.org\/project\/javascript\/\" target=\"_blank\" rel=\"noopener\"><code>javascript<\/code> module<\/a>, which is a dependency of JSPyBridge.<\/p>\n<p>First, create the project directory and change into the directory with the following command:<\/p>\n<pre class=\"language-bash hljs\">mkdir python_demo &amp;&amp; cd python_demo\n<\/pre>\n<p>Since this is a Python directory, create a virtual environment for the project:<\/p>\n<pre class=\"language-bash hljs\">python3 -m venv venv\n<\/pre>\n<p>Activate the virtual environment:<\/p>\n<pre class=\"language-bash hljs\">source venv\/bin\/activate\n<\/pre>\n<p>With the virtual environment created, install the <code>javascript<\/code> module:<\/p>\n<pre class=\"language-bash hljs\">pip3 install javascript\n<\/pre>\n<p>Now that we have our environment set up, we will begin interoperating Node.js with Python.<\/p>\n<h3 id=\"importing-javascript-function-python\">Importing a JavaScript function in Python<\/h3>\n<p>Let\u2019s create and call a JavaScript function in Python. The function will format an integer value into the currency of your choosing. You\u2019ll then import the JavaScript function in Python, pass arguments into it, and print the return value.<\/p>\n<p>Open the <code>formatCurrency.js<\/code> file in your editor and add the following:<\/p>\n<pre class=\"language-javascript hljs\">function formatCurrency(value, type) {\n  format = new Intl.NumberFormat(\"en-US\", {\n    style: \"currency\",\n    currency: type,\n  }).format;\n  return format(value);\n}\nmodule.exports = { formatCurrency };\n<\/pre>\n<p>In the preceding code block, we defined a <code>formatCurrency()<\/code> function, which takes two arguments:<\/p>\n<ol>\n<li><code>value<\/code>, the amount of money<\/li>\n<li><code>type<\/code>, the currency we want the amount to be formatted to<\/li>\n<\/ol>\n<p>Within the function, we create an <code>Intl.NumberFormat<\/code> instance, which takes the language <code>en-US<\/code> as the first argument, and an object containing formatting options as a second argument.<\/p>\n<p>The object has two properties: <code>style<\/code> and <code>currency<\/code>. The <code>style<\/code> property accepts the formatting style, which is the <code>currency<\/code> string here. The <code>currency<\/code> property accepts the currency name in short form, which is stored in the <code>type<\/code> variable.<\/p>\n<p>Upon creating the <code>Intl.NumberFormat<\/code> instance, a function is returned and stored in the <code>format<\/code> variable. Next, you invoke the <code>format()<\/code> function with the <code>value<\/code> parameter as the argument. Once the <code>format()<\/code> function runs, the <code>formatCurrency()<\/code> function returns the result. Finally, we export the function <code>formatCurrency()<\/code> so that it can be used in Python.<\/p>\n<p>Now that the function has been defined, we will reference it in Python. Open and create the <code>format_currencies.py<\/code> file in your editor and add the following:<\/p>\n<pre class=\"language-python hljs\">from javascript import require\n\ndata = require(\".\/formatCurrency.js\")\n\nvalue = 2000000\n\nprint(data.formatCurrency(value, \"USD\"))\nprint(data.formatCurrency(value, \"EUR\"))\n<\/pre>\n<p>First, we import the <code>require<\/code> method from the <code>javascript<\/code> module. Next, we call the <code>require()<\/code> method with the path to the JavaScript file <code>formatCurrency.js<\/code>. After that, we define an integer and store it in the <code>value<\/code> variable. In the last two lines, we call the <code>formatCurrency()<\/code> with the <code>value<\/code> variable and the currency we want.<\/p>\n<p>Now, run the <code>format_currency.py<\/code> file:<\/p>\n<pre class=\"language-bash hljs\">python3 format_currencies.py\n<\/pre>\n<p>Upon running the file, you\u2019ll see output that looks like this:<\/p>\n<pre class=\"language-plaintext hljs\">$2,000,000.00\n\u20ac2,000,000.00\n<\/pre>\n<p>This shows that Python called the JavaScript function, retrieved the return value, and logged it in the terminal.<\/p>\n<h3 id=\"importing-using-node-js-packages-python\">Importing and Using Node.js Packages in Python<\/h3>\n<p>Node.js has numerous packages that you can use in your projects, and JSPyBridge allows you to import and use them in Python. You don\u2019t even have to install them using npm \u2014 when you invoke the <code>require()<\/code> method with the package name, JSPyBridge will automatically fetch the package for you.<\/p>\n<p>In this section, we will use the <a href=\"https:\/\/www.npmjs.com\/package\/sqlstring\" target=\"_blank\" rel=\"noopener\">sqlstring<\/a> npm package in Python. The <code>sqlstring<\/code> module can be used to escape and format SQL statements for MySQL.<\/p>\n<p>Open the <code>generateSQL.py<\/code> file in your text editor:<\/p>\n<pre class=\"language-python hljs\">from javascript import require\n\nsqlString = require(\"sqlstring\")\n\nname = input(\"What is your name?n\")\nsql = sqlString.format(\"SELECT *  FROM customers WHERE name = ?\", [name])\n\nprint(sql)\n<\/pre>\n<p>First, we import the <code>require<\/code> method from the <code>javascript<\/code> module. Second, we call the <code>require()<\/code> method with the <code>sqlstring<\/code> as the argument. Next, we call Python\u2019s <code>input()<\/code> method to get user input, and after that, we invoke the <code>format()<\/code> method of the <code>sqlstring<\/code> module, which takes an SQL query as the argument. Finally, we print the formatted SQL query.<\/p>\n<p>Now run the file and enter a name when the prompt shows up:<\/p>\n<pre class=\"language-bash hljs\">python3 generateSQL.py\n<\/pre>\n<p>Running the file produces an output that looks like the following:<\/p>\n<pre class=\"language-plaintext hljs\"> Installing 'sqlstring' version 'latest'... This will only happen once.\n\nadded 1 package, and audited 2 packages in 502ms\n\nfound 0 vulnerabilities\n\n OK.\nWhat is your name?\njohn\n\nSELECT *  FROM customers WHERE name = 'john'\n<\/pre>\n<p>Notice in the output that when you first run the file, JSPyBridge downloaded the package. Once downloaded, the module was used to generate a SQL statement, which Python logged in the terminal.<\/p>\n<h3 id=\"using-es2015-python\">Using ES2015 in Python<\/h3>\n<p>In this section, we will import an ECMAScript 2015 (ES6) class, instantiate it, and then call the instance method in Python.<\/p>\n<p>Create a new file named <code>person.js<\/code>:<\/p>\n<pre class=\"language-javascript hljs\">class Person {\n  constructor(firstName, lastName) {\n    this.firstName = firstName;\n    this.lastName = lastName;\n  }\n\n  getFullName() {\n    return `${this.firstName} ${this.lastName}`;\n  }\n}\n\nmodule.exports = { Person };\n<\/pre>\n<p>The <code>Person<\/code> class takes two arguments: <code>firstName<\/code> and <code>lastName<\/code>. It also has a <code>getFullName()<\/code> method that concatenates the <code>firstName<\/code> and the <code>lastName<\/code> arguments to produce a full name.<\/p>\n<p>To use the class in Python, we export it using <code>module.exports<\/code>. Now, create another file <code>create_person.py<\/code> file in your editor and add the following contents:<\/p>\n<pre class=\"language-python hljs\">from javascript import require\n\ndata = require(\".\/person.js\")\nperson_one = data.Person.new(\"John\", \"Doe\")\nprint(person_one.getFullName())\n<\/pre>\n<p>Here, we import <code>require()<\/code> and reference the JavaScript file <code>person.js<\/code>. Next, we create an instance of the class <code>Person<\/code> by invoking the <code>new()<\/code> method, which takes the first name and the last name as the arguments. Finally, we invoke the <code>getFullName()<\/code> method of the <code>Person<\/code> class and print the return value in the terminal.<\/p>\n<p>Save your file and run <code>person.py<\/code>:<\/p>\n<pre class=\"language-bash hljs\">python3 create_person.py\n<\/pre>\n<p>Running the file will yield the following output:<\/p>\n<pre class=\"language-plaintext hljs\">John Doe\n<\/pre>\n<p>The output shows that the name first name and last name have been concatenated. This confirms that we can invoke and use JavaScript ES2015 classes in Python.<\/p>\n<h3 id=\"using-javascript-iterables-Python\">Using JavaScript iterables in Python<\/h3>\n<p>Let\u2019s create an array in Node.js, export it, and iterate over it in Python. We will build upon the <code>formatCurrency.js<\/code> program and make use of the <code>formatCurrency()<\/code> function to format multiple values and append them to an array. The array will be exported and iterated in Python.<\/p>\n<p>Create the following file <code>formatValues.js<\/code> with the following contents:<\/p>\n<pre class=\"language-javascript hljs\">values = [200, 40000000, 2938, 80999];\nusd_values = [];\nfunction formatCurrency(value, type) {\n  format = new Intl.NumberFormat(\"en-US\", {\n    style: \"currency\",\n    currency: type,\n  }).format;\n  return format(value);\n}\n\nfor (let i = 0; i &lt; values.length; i++) {\n  usd_values.push(formatCurrency(values[i], \"USD\"));\n}\n\nmodule.exports = { items: usd_values };\n<\/pre>\n<p>We create a <code>values<\/code> array that contains numbers to be formatted as currency. Next, we define an empty array, <code>usd_values<\/code> values, and the <code>formatCurrency()<\/code> function that formats the given value in the currency of your choice.<\/p>\n<p>Following this, we iterate over the <code>values<\/code> array, and during each iteration, we call the <code>formatCurrency()<\/code> function and push the formatted value into the <code>usd_values<\/code> array. Once the loop finishes, we export an object that has an <code>items<\/code> property, whose value is the <code>usd_values<\/code> array.<\/p>\n<p>Next, we will import the array in Python. Create the <code>list_currencies.py<\/code> file with the following contents:<\/p>\n<pre class=\"language-python hljs\">from javascript import require\n\ndata = require(\".\/formatValues.js\")\nfor item in data.items:\n    print(item)\n<\/pre>\n<p>First, we reference the <code>formatValues.js<\/code> file. Next, we iterate over the Node.js array and print the value during each iteration.<\/p>\n<p>Now, run the file using the <code>python3<\/code> command:<\/p>\n<pre class=\"language-bash hljs\">python3 list_currencies.py\n<\/pre>\n<p>When you run the command, you will see an output that resembles the following:<\/p>\n<pre class=\"language-plaintext hljs\">$200.00\n$40,000,000.00\n$2,938.00\n$80,999.00\n<\/pre>\n<p>The output confirms that we can iterate over a JavaScript array in Python.<\/p>\n<h3 id=\"importing-javascript-file-python-different-directory\">Importing a JavaScript file in Python from a different directory<\/h3>\n<p>So far, we looked at how to import functions, classes, and iterables from Node.js, and run them in Python within the same project directory. In this section, we will import a Node.js array that resides in another directory into Python and loop through each element.<\/p>\n<p>First, move out of the project directory:<\/p>\n<pre class=\"language-bash hljs\">cd ..\n<\/pre>\n<p>Next, create a new project directory and move into the directory:<\/p>\n<pre class=\"language-bash hljs\">mkdir currency_app &amp;&amp; cd currency_app\n<\/pre>\n<p>Initialize the directory as an npm project:<\/p>\n<pre class=\"language-bash hljs\">npm init -y\n<\/pre>\n<p>Next, install the <code>[uuid](https:\/\/www.npmjs.com\/package\/uuid)<\/code> <a href=\"https:\/\/www.npmjs.com\/package\/uuid\">package<\/a>, which generates a Universal Unique Identifier (UUID) that you can use to uniquely identify objects:<\/p>\n<pre class=\"language-bash hljs\">npm install uuid\n<\/pre>\n<p>Next, create a new file, <code>formatValues.js<\/code>, and add the following:<\/p>\n<pre class=\"language-javascript hljs\">const { v4: uuidv4 } = require(\"uuid\");\n\nvalues = [200, 40000000, 2938, 80999];\nusd_values = [];\nfunction formatCurrency(value, type) {\n  format = new Intl.NumberFormat(\"en-US\", {\n    style: \"currency\",\n    currency: type,\n  }).format;\n  return format(value);\n}\n\nfor (let i = 0; i &lt; values.length; i++) {\n  usd_values.push({\n    id: uuidv4(),\n    currency: formatCurrency(values[i], \"USD\"),\n  });\n}\n\nconsole.log(usd_values);\n\nmodule.exports = { items: usd_values };\n<\/pre>\n<p>The file reuses a lot of code we had in the previous section; however, there are new changes. First, we import the UUID module. In the <code>for<\/code> loop, instead of pushing only the values, we create an object with the following properties: <code>id<\/code> and <code>currency<\/code>.<\/p>\n<p>The <code>id<\/code> property is assigned a UUID, generated by calling the <code>uuidv4()<\/code> function of the UUID module. The <code>currency<\/code> property is assigned a value returned from calling the <code>formatCurrency()<\/code> function. Finally, we have a <code>console.log()<\/code> method that logs the <code>usd_values<\/code> array in the console.<\/p>\n<p>With that, run the file using the <code>node<\/code> command:<\/p>\n<pre class=\"language-bash hljs\">node formatValues.js\n<\/pre>\n<p>You will see an output that looks like the following:<\/p>\n<pre class=\"language-plaintext hljs\">[\n  { id: 'bfdb0bd6-0e9a-4275-812f-dd1b81dde930', currency: '$200.00' },\n  {\n    id: '31b0d44a-8987-4f50-a683-99f4af477e6d',\n    currency: '$40,000,000.00'\n  },\n  { id: 'ab9f0e76-875d-4e77-8bb9-61015b8a1a46', currency: '$2,938.00' },\n  {\n    id: 'f035883d-952a-4642-8c66-379858601f5f',\n    currency: '$80,999.00'\n  }\n]\n<\/pre>\n<p>The output shows confirm that the objects are being created with the UUIDs.<\/p>\n<p>Now, remove the <code>console.log()<\/code> method in the <code>formatValues.js<\/code> file. We don\u2019t need it anymore, since the array contents will be displayed in Python.<\/p>\n<p>Now that we know the program runs successfully, we will import the array into the main project directory, <code>python_demo<\/code>.<\/p>\n<p>Return to the main project directory:<\/p>\n<pre class=\"language-bash hljs\">cd .. &amp;&amp; cd python_demo\n<\/pre>\n<p>In the project directory, create a <code>list_usd_values_with_uuid.py<\/code> file in your editor with the following:<\/p>\n<pre class=\"language-python hljs\">from javascript import require\n\ndata = require(\".\/..\/currency_app\/formatValues.js\")\nfor item in data.items:\n    print(f'ID: {item.id}')\n    print(f'Amount in USD: {item.currency}')\n    print(\"n\")\n<\/pre>\n<p>In the code block, we reference <code>formatCurrencies.js<\/code>, which resides in another directory. Next, we iterate over all elements in the array, and print the item UUID and the formatted currency in the console.<\/p>\n<p>Now, run the <code>list_usd_values_with_uuid.py<\/code> file:<\/p>\n<pre class=\"language-bash hljs\">python list_usd_values_with_uuid.py\n<\/pre>\n<p>Running the code yields the following:<\/p>\n<pre class=\"language-plaintext hljs\">ID: 35295372-eedc-44bd-8e19-360a990a1a44\nAmount in USD: $200.00\n\n\nID: c446ae79-3904-4c8b-8e74-31d4184612ca\nAmount in USD: $40,000,000.00\n\n\nID: 13ce5e1a-7f0a-4d81-bfd4-d18229a1b159\nAmount in USD: $2,938.00\n\n\nID: 755e1f39-3cad-4128-b806-4681acccd7d7\nAmount in USD: $80,999.00\n<\/pre>\n<p>As you can see in the output, we can successfully iterate over an array that is in another project directory.<\/p>\n<p>Now that you know how to use JSPyBridge to access Node.js API in Python, we\u2019re going to access the Python API in the next section.<\/p>\n<h2 id=\"accessing-python-node-js\">Accessing Python in Node.js<\/h2>\n<p>In this section, we will access Python modules, local Python files, functions, classes, and iterables in Node.js. To do this, we will create another directory that will contain our Node.js code, as well as the Python files.<\/p>\n<p>First, move out of the current directory and go back to the home directory:<\/p>\n<pre class=\"language-bash hljs\">cd ..\n<\/pre>\n<p>Now, in the home directory, create a new directory and change into it:<\/p>\n<pre class=\"language-bash hljs\">mkdir node_demo &amp;&amp; cd node_demo\n<\/pre>\n<p>Since this is a Node.js directory, initialize <code>npm<\/code>:<\/p>\n<pre class=\"language-bash hljs\">npm init -y\n<\/pre>\n<p>Next, install the <a href=\"https:\/\/www.npmjs.com\/package\/pythonia\" target=\"_blank\" rel=\"noopener\">pythonia package<\/a>, which is a bridge for Node.js:<\/p>\n<pre class=\"language-bash hljs\">npm install pythonia\n<\/pre>\n<p>Next, add the <code>\"type\": \"module\"<\/code> line at the end of your <code>package.json<\/code> to allow Node.js to use ES2015 modules:<\/p>\n<pre class=\"language-json hljs\">{\n  ...\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"pythonia\": \"^1.0.0\"\n  },\n  \"type\": \"module\"\n}\n<\/pre>\n<p>With that, you are now set to use JSPyBridge in Node.js. Next, we will import a Python function and invoke it in Node.js.<\/p>\n<h3 id=\"importing-python-function-node-js\">Importing a Python function in Node.js<\/h3>\n<p>In this section, we will create a function in Python, import it, and then run the function in Node.js. The function will make use of the <a href=\"https:\/\/docs.python.org\/3\/library\/random.html\" target=\"_blank\" rel=\"noopener\"><code>random<\/code> module<\/a> in Python.<\/p>\n<p>Create a <code>random_choices.py<\/code> file and add the following:<\/p>\n<pre class=\"language-python hljs\">import random\n\n\ndef get_random_word():\n    colors = [\"red\", \"green\", \"blue\", \"yellow\"]\n    return random.choice(colors)\n<\/pre>\n<p>In the first line, import the <code>random<\/code> module from Python. We then define a function, <code>get_random_word()<\/code>, which shuffles and returns a random value in the <code>colors<\/code> array.<\/p>\n<p>Next, create the <code>pickRandomValue.js<\/code> file with the following code:<\/p>\n<pre class=\"language-javascript hljs\">import { python } from \"pythonia\";\nconst rand = await python(\".\/random_choices.py\");\nconsole.log(await rand.get_random_word());\npython.exit();\n<\/pre>\n<p>Import the <code>python<\/code> function from the <code>pythonia<\/code> package. Next, call the <code>python()<\/code> function with the <code>random_choices.py<\/code> path as the argument, which then starts a Python process.<\/p>\n<p>In Node.js, JSPyBridge requires that every Python API call be prefixed with the <code>await<\/code> keyword. Following this, we call the <code>get_random_word()<\/code> function and log the result into the terminal. Finally, we exit the process.<\/p>\n<p>Now, run the file with the <code>node<\/code> command:<\/p>\n<pre class=\"language-bash hljs\">node pickRandomValue.js\n<\/pre>\n<p>When you run the command, you will see output that looks similar to this:<\/p>\n<pre class=\"language-bash hljs\">red\n<\/pre>\n<p>The output shows <code>red<\/code>. Yours might show a different color because, after all, the package returns random values.<\/p>\n<h3 id=\"working-python-third-party-modules-node-js\">Working with Python third-party modules in Node.js<\/h3>\n<p>In this section, we will work with third-party Python modules in Node.js. Our program will use <a href=\"https:\/\/matplotlib.org\/\" target=\"_blank\" rel=\"noopener\">Matplotlib<\/a> and <a href=\"https:\/\/numpy.org\/\" target=\"_blank\" rel=\"noopener\">NumPy<\/a> to create a graph.<\/p>\n<p>First, deactivate the current virtual environment:<\/p>\n<pre class=\"language-bash hljs\">deactivate\n<\/pre>\n<p>Create a new virtual environment in the directory:<\/p>\n<pre class=\"language-bash hljs\">python3 -m venv venv\n<\/pre>\n<p>Activate the virtual environment:<\/p>\n<pre class=\"language-bash hljs\">source venv\/bin\/activate\n<\/pre>\n<p>Next, install the following modules with the following command:<\/p>\n<pre class=\"language-bash hljs\">pip3 install numpy matplotlib\n<\/pre>\n<p>To use the modules in JavaScript, create a <code>plot_graph.js<\/code> file and add the following:<\/p>\n<pre class=\"language-javascript hljs\">import { python } from 'pythonia'\nconst np = await python('numpy')\nconst plt = await python('matplotlib.pyplot')\n\n\nconst x = await np.array([1, 2, 3])\nconst y = await np.array([4, 1, 2])\n\nawait plt.plot(x, y)\n\nawait plt.title('matplotlib graph in Node.js')\n\nawait plt.savefig('graph.png')\npython.exit()\n<\/pre>\n<p>First, we import the <code>python()<\/code> function from <code>pythonia<\/code>. In the next two lines, we call the <code>python<\/code> function to import NumPy and Matplotlib modules.<\/p>\n<p>Next, we define arrays using the <code>np.array()<\/code> method, which are stored in the <code>x<\/code> and <code>y<\/code> variables. Following this, we invoke <code>plt.plot()<\/code>, which takes the arrays in <code>x<\/code> and <code>y<\/code> variables as arguments. After that, we use the <code>plt.title()<\/code> method to define the title of the graph. We then invoke <code>plt.savefig()<\/code> to save the graph as an image in the directory. Finally, we exit the Python process.<\/p>\n<p>Now, run the file:<\/p>\n<pre class=\"language-bash hljs\">node plot_graph.js\n<\/pre>\n<p>When the command runs, you will have an image, <code>graph.png<\/code>, in your directory that looks like this:<br>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-133031 size-full\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/matplotlib-graph-generated-node-js-2-1.png\" alt=\"Matplotlib Graph in Node.js\" width=\"730\" height=\"548\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/matplotlib-graph-generated-node-js-2-1.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/matplotlib-graph-generated-node-js-2-1-300x225.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<h3 id=\"using-python-classes-node-js\">Using Python classes in Node.js<\/h3>\n<p>In this section, we will define a class in Python and instantiate it in Node.js.<\/p>\n<p>Create the <code>person.py<\/code> file with the following contents:<\/p>\n<pre class=\"language-python hljs\">class Person:\n    def __init__(self, firstName, lastName):\n        self.firstName = firstName\n        self.lastName = lastName\n\n    def getFullName(self):\n        return f\"{self.firstName} {self.lastName}\"\n<\/pre>\n<p>The Python class is analogous to the ES2015 <code>Person<\/code> class we defined earlier. The class takes two arguments: <code>firstName<\/code> and <code>lastName<\/code>. It also has a <code>getFullName()<\/code> method that returns the full name of the person.<\/p>\n<p>To use the <code>Person<\/code> class in Node.js, import the <code>createPerson.js<\/code> file:<\/p>\n<pre class=\"language-javascript hljs\">import { python } from \"pythonia\";\nconst data = await python(\".\/person.py\");\nconst person1 = await data.Person(\"John\", \"Doe\");\nconsole.log(await person1.getFullName());\npython.exit();\n<\/pre>\n<p>First, we import the <code>Python<\/code> function from <code>pythonia<\/code> and then reference the <code>person.py<\/code> file. Second, we create an instance by calling <code>Person<\/code> class with the first name and the last name as the arguments. We call <code>getFullName()<\/code> method, which returns the full name, which we then print in the console. Finally, as always, we exit the Python process.<\/p>\n<p>Now, run the file using <code>node<\/code>:<\/p>\n<pre class=\"language-bash hljs\">node createPerson.js\n<\/pre>\n<p>It will yield an output that looks like the following:<\/p>\n<pre class=\"language-bash hljs\">John Doe\n<\/pre>\n<p>This shows that we can successfully use Python classes in Node.js.<\/p>\n<h3 id=\"using-python-iterables-node-js\">Using Python iterables in Node.js<\/h3>\n<p>In this section, we will create a list in Python, and loop through each element in Node.js.<\/p>\n<p>First, create <code>get_dir_contents.py<\/code> with the following:<\/p>\n<pre class=\"language-python hljs\">import os\n\ndir_files = os.listdir(\".\/node_modules\")\n<\/pre>\n<p>We begin by importing the <code>os<\/code> module. Next, we call <code>listdir()<\/code> method of the <code>os<\/code> module which returns a list of all the files in the given directory <code>node_modules<\/code>.<\/p>\n<p>Now that we have the list in Python, we will import it and call it in Node.js.<\/p>\n<p>First, create the <code>listDir.js<\/code> file and add the following:<\/p>\n<pre class=\"language-javascript hljs\">import { python } from \"pythonia\";\nconst obj = await python(\".\/get_dir_contents.py\");\nconst dirFiles = await obj.dir_files;\n\nfor await (const file of dirFiles) {\n  console.log(file);\n}\n\npython.exit();\n<\/pre>\n<p>First, we reference the <code>listDir.py<\/code> file using the <code>python()<\/code> function that we imported in the first line. Next, we unpack the <code>dir_files<\/code> array and store it in the <code>dirFiles<\/code> variable.<\/p>\n<p>After that, we define a <code>for await<\/code> loop to loop through all the elements and log each file in the console during each iteration. JSPyBridge does not recommend using other loops when looping through an array from Python.<\/p>\n<p>Next, run the <code>listDir.js<\/code> file:<\/p>\n<pre class=\"language-bash hljs\">node listDir.js\n<\/pre>\n<p>When the command runs, you will see output resembling the following:<\/p>\n<pre class=\"language-plaintext hljs\">ansi-styles\ncolor-name\nhas-flag\nws\npythonia\nchalk\n.package-lock.json\ncaller\nsupports-color\ncolor-convert\n<\/pre>\n<p>This shows that Node.js can loop through Python arrays.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we learned how to use JSPyBridge to interoperate Node.js and Python. In the first half, we looked at how to use JSPyBridge in Python. We learned how to import and use the following:<\/p>\n<table>\n<thead>\n<tr>\n<th>Node.js in Python<\/th>\n<th>Python in Node.js<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>\n<ul>\n<li>functions<\/li>\n<li>Node.js packages<\/li>\n<li>ES2015 classes<\/li>\n<li>iterables<\/li>\n<li>Node.js files in other project folders<\/li>\n<\/ul>\n<\/td>\n<td>\n<ul>\n<li>functions<\/li>\n<li>classes<\/li>\n<li>iterables<\/li>\n<li>third-party modules<\/li>\n<\/ul>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>To learn more about JSPyBridge, visit the <a href=\"https:\/\/github.com\/extremeheat\/JSPyBridge\" target=\"_blank\" rel=\"noopener\">JSPyBridge documentation<\/a>. You can also check out more <a href=\"https:\/\/github.com\/extremeheat\/JSPyBridge\/tree\/master\/examples\" target=\"_blank\" rel=\"noopener\">examples in their GitHub repo<\/a>. If you want to learn how to use Python in the frontend, see <a href=\"https:\/\/blog.logrocket.com\/pyscript-run-python-browser\/\" target=\"_blank\" rel=\"noopener\">the PyScript tutorial<\/a>.<\/p>\n<\/html>\n","protected":false},"excerpt":{"rendered":"<p>JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.<\/p>\n","protected":false},"author":156415879,"featured_media":132769,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2147999,1],"tags":[2109828,2109699,2109833],"class_list":["post-132353","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dev","category-uncategorized","tag-js-libraries","tag-node","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.1.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Exploring JSPyBridge, a new library for using Python in JavaScript - LogRocket Blog<\/title>\n<meta name=\"description\" content=\"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Exploring JSPyBridge, a new library for using Python in JavaScript - LogRocket Blog\" \/>\n<meta property=\"og:description\" content=\"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/\" \/>\n<meta property=\"og:site_name\" content=\"LogRocket Blog\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-20T16:00:09+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-06-04T21:04:47+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png\" \/>\n\t<meta property=\"og:image:width\" content=\"730\" \/>\n\t<meta property=\"og:image:height\" content=\"487\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Stanley Ulili\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Stanley Ulili\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"15 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/\",\"url\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/\",\"name\":\"Exploring JSPyBridge, a new library for using Python in JavaScript - LogRocket Blog\",\"isPartOf\":{\"@id\":\"https:\/\/blog.logrocket.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png\",\"datePublished\":\"2022-09-20T16:00:09+00:00\",\"dateModified\":\"2024-06-04T21:04:47+00:00\",\"author\":{\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/c497a1b0563997bd4f811cfb05e48b9c\"},\"description\":\"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.\",\"breadcrumb\":{\"@id\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#primaryimage\",\"url\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png\",\"contentUrl\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png\",\"width\":730,\"height\":487,\"caption\":\"Exploring JSpyBridge, a new library for using Python in Javascript\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/blog.logrocket.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Exploring JSPyBridge, a new library for using Python in JavaScript\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/blog.logrocket.com\/#website\",\"url\":\"https:\/\/blog.logrocket.com\/\",\"name\":\"LogRocket Blog\",\"description\":\"Resources to Help Product Teams Ship Amazing Digital Experiences\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/blog.logrocket.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/c497a1b0563997bd4f811cfb05e48b9c\",\"name\":\"Stanley Ulili\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/df8e4b704eb287a023fb2b6e3dff5b2d3748f077387f72a36cc82eea9d62132c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/df8e4b704eb287a023fb2b6e3dff5b2d3748f077387f72a36cc82eea9d62132c?s=96&d=mm&r=g\",\"caption\":\"Stanley Ulili\"},\"description\":\"I'm a freelance web developer and researcher from Malawi. I love learning new things, and writing helps me understand and solidify concepts. I hope by sharing my experience, others can learn something from them.\",\"sameAs\":[\"https:\/\/www.stanleyulili.com\/\"],\"url\":\"https:\/\/blog.logrocket.com\/author\/stanleyulili\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Exploring JSPyBridge, a new library for using Python in JavaScript - LogRocket Blog","description":"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/","og_locale":"en_US","og_type":"article","og_title":"Exploring JSPyBridge, a new library for using Python in JavaScript - LogRocket Blog","og_description":"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.","og_url":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/","og_site_name":"LogRocket Blog","article_published_time":"2022-09-20T16:00:09+00:00","article_modified_time":"2024-06-04T21:04:47+00:00","og_image":[{"width":730,"height":487,"url":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png","type":"image\/png"}],"author":"Stanley Ulili","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Stanley Ulili","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/","url":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/","name":"Exploring JSPyBridge, a new library for using Python in JavaScript - LogRocket Blog","isPartOf":{"@id":"https:\/\/blog.logrocket.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#primaryimage"},"image":{"@id":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#primaryimage"},"thumbnailUrl":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png","datePublished":"2022-09-20T16:00:09+00:00","dateModified":"2024-06-04T21:04:47+00:00","author":{"@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/c497a1b0563997bd4f811cfb05e48b9c"},"description":"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.","breadcrumb":{"@id":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#primaryimage","url":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png","contentUrl":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/exploring-jspybridge-using-python-javascript.png","width":730,"height":487,"caption":"Exploring JSpyBridge, a new library for using Python in Javascript"},{"@type":"BreadcrumbList","@id":"https:\/\/blog.logrocket.com\/exploring-jspybridge-library-python-javascript\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blog.logrocket.com\/"},{"@type":"ListItem","position":2,"name":"Exploring JSPyBridge, a new library for using Python in JavaScript"}]},{"@type":"WebSite","@id":"https:\/\/blog.logrocket.com\/#website","url":"https:\/\/blog.logrocket.com\/","name":"LogRocket Blog","description":"Resources to Help Product Teams Ship Amazing Digital Experiences","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blog.logrocket.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/c497a1b0563997bd4f811cfb05e48b9c","name":"Stanley Ulili","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/df8e4b704eb287a023fb2b6e3dff5b2d3748f077387f72a36cc82eea9d62132c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/df8e4b704eb287a023fb2b6e3dff5b2d3748f077387f72a36cc82eea9d62132c?s=96&d=mm&r=g","caption":"Stanley Ulili"},"description":"I'm a freelance web developer and researcher from Malawi. I love learning new things, and writing helps me understand and solidify concepts. I hope by sharing my experience, others can learn something from them.","sameAs":["https:\/\/www.stanleyulili.com\/"],"url":"https:\/\/blog.logrocket.com\/author\/stanleyulili\/"}]}},"yoast_description":"JSPyBridge lets you interoperate between Node.js and Python \u2014 access and use JS functions, packages, classes, and arrays in Python and vice versa.","_links":{"self":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/132353","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/users\/156415879"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/comments?post=132353"}],"version-history":[{"count":30,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/132353\/revisions"}],"predecessor-version":[{"id":133373,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/132353\/revisions\/133373"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/media\/132769"}],"wp:attachment":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/media?parent=132353"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/categories?post=132353"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/tags?post=132353"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}