Transmitting data from Node.js to Python (One Way Communication)
What we are going to learn?
In this blog, we will learn to develop a pipeline to transmit data from Node.js (Javascript) to Python.
Why do we need pipelining?
To develop a “Remote Desktop Application” using Javascript (Node.js) we need Python’s support because by using python we can utilize the PyAutoGUI library and this library helps us to control our PC or Laptop programmatically. Nodejs is also having a similar kind of library called RobotJS but if have to use this library we have to install prebuilt binaries for our OS. Personally, I tried to utilize the RobotJS library but unfortunately, it's not working properly.
So to solve this issue we are dependent on Python’s PyAutoGUI and mainly we are developing our application entirely on Javascript. Also, we will get the Mouse coordinates & Key events from the client application over Javascript via WebRTC. Hence to transmit these events towards Python we need pipelining (IPC).
In my previous blog, “Build Your Own Remote Desktop Application using Javascript, Python & WebRTC — Part 2” we learned to establish a communication between Javascript & Python by using WebSocket to integrate mouse click event functionality on Screen Share API.
But I have identified that WebSocket-based communication has some latency while transmitting data and it will affect our application performance. Hence we are going to implement the pipelining concept in a different way.
What are we going to do?
To implement faster communication (pipelining) between Javascript (Node.js) & Python we are going to use ExpressJS and Requests libraries. And one good thing is we can do this only with minimal coding.
Note: This is a one-way communication (Only to transmit data from Js to Py).
Let us code . . . 🎨
Create server using Express JS
/* index.js */const express = require('express');
const app = express();
const port = process.env.PORT || 3000;let value = nullapp.get('/:set', (req, res) => {
value = req.params.set
res.send('Ok')
})app.get('/', (req, res) => {
res.send(value)
})app.listen(port);
console.log('Server started at http://localhost:' + port);
Create python script to receive data
# agent.py #import requestswhile 1:
try:
result = requests.get('http://localhost:3000/')
print(result.text)
except:
pass
Explanation:
- By using the Express JS library we are creating a server that will send a response to the request.
- In Python, with help of the Requests library, we created a program that will receive a response and deliver the output using a print statement.
- To keep the request listening process open we added the code inside try & except block which will handle the error and keep it open.
Conclusion:
In my upcoming blog, we will learn to implement this pipelining concept with the PyAutoGUI library to control our PC / Laptop remotely from other devices.