Rewrite this to JavaScript (nodejs): [code]
- User
Rewrite this to JavaScript (nodejs):
pythonimport csv import socket import struct import urllib.parse import pycountry import ipwhois import whois import json from ipaddress import IPv4Address, AddressValueError def get_country_name(iso_code): try: country = pycountry.countries.get(alpha_2=iso_code) if country: return country.name else: return 'Country not found' except Exception as e: return str(e) def cidr_to_netmask(cidr): network, net_bits = cidr.split('/') host_bits = 32 - int(net_bits) netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits))) return network, netmask def ip_range_to_cidr(ip_start, ip_end): start = ip_to_int(ip_start) end = ip_to_int(ip_end) prefix_length = 32 - (end - start).bit_length() return f"{ip_start}/{prefix_length}" def ip_to_int(ip_address): parts = ip_address.split('.') return (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3]) def array_to_json_object(data): """ Converts an array of objects to a JSON object with numeric keys. """ result = {} for index, item in enumerate(data, start=1): result[str(index)] = item return result def save_to_json(data, filename): """ This function saves a Python object to a JSON file. Args: data: The Python object to be saved (string in this case). filename: The name of the output JSON file. """ with open(filename, 'w') as outfile: json.dump(data, outfile) def process_csv_data(input_file): """ This function processes a CSV file and returns an object array containing IP addresses, subnet masks (optional), and countries. Args: input_file: Path to the CSV file. Returns: An array of objects containing address, subnet_mask (optional), and country information. """ data = [] with open(input_file, 'r', newline='') as infile: reader = csv.reader(infile) index = 1 for row in reader: try: # Extract ip address and cidr address = cidr_to_netmask(row[0]) ip = IPv4Address(address[0]) net_name = ipwhois.IPWhois(address[0]).lookup_whois()['nets'][0]['name'] ban_reason = f'[W] {get_country_name(row[1])} ({net_name.upper()})' # Create an object and append it to the data array data.append({ "ip": f"{ip}", "subnet": f"{address[1]}", "time": "", "reason": f"{ban_reason}", "comment": "", "isEdited": False }) index = index + 1 except (IndexError, ValueError, AddressValueError): # Handle potential errors like missing cells or invalid subnet mask format pass return data # Example usage input_file = "geofeed.csv" filename = "output.json" processed_data = process_csv_data(input_file) save_to_json(array_to_json_object(processed_data), filename) print(array_to_json_object(processed_data)) # [{'address': '127.0.0.0/8', 'country': 'RU'}, ...] - Assistant
- User
Use whois-json instead of ipwhois
- Assistant