How to Get the Latest Versions of Multiple npm Packages

In this blog post, we will learn how to get the latest versions of multiple npm packages using Python.

Import libraries:

import json
import requests
from requests.exceptions import HTTPError

Write a function fetching the latest version

Next, we need to define a function called get_latest_npm_versions(). This function will take a list of npm package names as input and return a list of tuples, where each tuple contains the package name and the latest version available:

def get_latest_npm_versions(npm_packages):
    latest_versions = []
    for package in npm_packages:
        url = f"https://registry.npmjs.org/{package}/latest"
        try:
            # Make an HTTP request to the npm registry to get the package info
            response = requests.get(url)

            # Check if the request was successful
            response.raise_for_status()

            # Parse the JSON response to get the package info
            package_info = json.loads(response.content)

            # Get the latest version of the package
            latest_version = package_info["version"]

            # Add the package and its latest version to the list
            latest_versions.append((package, latest_version))
        except HTTPError:
            # If the request was not successful, add the package and an error message to the list
            latest_versions.append((package, 'HTTPError'))

    return latest_versions

Read package names from input.txt, fetch the latest, and write to output.txt

Now, we can use the get_latest_npm_versions() function to get the latest versions of multiple npm packages.

// input.text content:
// react
// react-dom
// redux

if __name__ == '__main__':
    print("Reading a list of packages from input.txt")
    # Read the list of packages from file input.txt
    with open("input.txt", "r") as f:
        npm_packages = f.readlines()
        npm_packages = [package.strip() for package in npm_packages]

    print("The list of packages is ready. Now getting the latest versions")

    # Get the latest versions of the packages
    latest_versions = get_latest_npm_versions(npm_packages)

    print("The list with latest versions is ready. Writing to output.txt")
    # Write the latest versions to file output.txt
    with open("output.txt", "w") as f:
        for package, version in latest_versions:
            f.write(f"{package}: {version}\n")

    # Print a success message
    print("Successfully wrote the latest versions of the packages to file output.txt")

Output.txt:

react: 18.1.0
react-dom: 18.1.0
redux: 4.2.0

Once the code has finished running, you can open the output.txt file to see the latest versions of the packages.

I hope this blog post has been helpful!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.