Integrating Node.js and Python for URL Shortening with pyshorteners

Introduction

In this blog post, we will explore the process of integrating Node.js and Python to create a simple URL shortening application using the pyshorteners library. By combining the strengths of both languages, we can leverage the powerful features of Node.js for managing the overall application and Python for the URL-shortening functionality.

URL Shorten

Node.js Script (nodeScript.js)

Let’s start by looking at the Node.js script, nodeScript.js. This script is responsible for spawning a Python process and passing a URL to be shortened as a command-line argument.

const { spawn } = require('child_process');
let urlToShorten = 'dynamitetechnology.in';
const pyProg = spawn('python', ['shortUrl.py', urlToShorten]);

pyProg.stdout.on('data', (data) => {
  console.log('Python script output:', data.toString());
});

pyProg.stderr.on('data', (data) => {
  console.error('Error from Python script:', data.toString());
});

pyProg.on('close', (code) => {
  console.log(`Python script exited with code ${code}`);
});

Explanation

  • The spawn function from the child_process module is used to execute the Python script (shortUrl.py).
  • The URL to be shortened ('dynamitetechnology.in' in this case) is passed as a command-line argument when spawning the Python process.
  • Event listeners are set up to capture the standard output and standard error streams from the Python process.

Python Script (shortUrl.py)

Now, let’s take a look at the Python script, shortUrl.py. This script utilizes the pyshorteners library to perform URL shortening.

import sys
import pyshorteners

# Check if a URL is provided as a command-line argument
if len(sys.argv) != 2:
    print("Usage: python shortUrl.py <url>")
    sys.exit(1)

url_to_shorten = sys.argv[1]

s = pyshorteners.Shortener()
print(s.tinyurl.short(url_to_shorten))

Explanation

  • The Python script checks whether a URL is provided as a command-line argument. If not, it prints a usage message and exits.
  • The provided URL is then passed to the pyshorteners library, and the shortened URL is printed to the console using the TinyURL service.

Conclusion

By combining Node.js and Python, we’ve created a simple yet effective URL-shortening application. Node.js handles the orchestration and communication with the Python script, while Python takes care of the URL shortening functionality. This integration showcases the versatility and interoperability of different programming languages, allowing developers to leverage the strengths of each for specific tasks within a single application.


Similar Articles